问:
PHPunit: How to change Mock object propriety from an external function
I am using Symfony and I'm trying to test the addStudentCard function in "Student" class, which adds a "StudentCard" object to $studentCards array collection propriety AND a "Student" object to $student propriety in "StudentCard" class. This is how I did it:

class StudentCard {
  private $student;
  public function getStudent();
  public function setStudent();
  //...
}

class Student {
  private $studentCards;
  public function getStudentCards();
  public function addStudentCard(StudentCard $studentCard){
    $studentCard->setStudent($this);
    $this->studentCards[] = $studentCard;
    return $this;
  //...
}
```

<p>What I want to achieve is to test this addStudentCard function using a MockBuilder, I have already done this without using mocks by doing:</p>

<pre class="lang-php prettyprint-override"><code>class StudentTest extends AbstractTestCase {
  public function testAddStudentCard(){
    $studentCard = new StudentCard();
    $student = new Student();
    $student->addStudentCard($studentCard);
    $student->assertSame($studentCard, $student->getStudentCards()[0]);
    $student->assertSame($student, $studentCard->getStudent());
}
</code>```

This works as expected with no problem.

What I would like is to replace the line:

$studentCard = new StudentCard();
```

<p>with something like this:</p>

<pre class="lang-php prettyprint-override"><code>$studentCard = $this->getMockBuilder(StudentCard::class)->getMock();
</code>```

But what I get is the error:
Failed asserting that null is identical to an object of class Student.

答:
The answer Ondrej Führer provided is the right answer to the problem I described.

I had also a removeStudentCard method that deletes the student from the studentCard object, so $this->once() was not appropriate for my case. In order to test this, I did exactly the same thing Ondrej Führer suggested with some modifications, so the code line I added was:

$studentCard->expects($this->exactly(2))->method('setStudent')->withConsecutive(
    [$student],
    [null]
);
//...
$student->addStudentCard($studentCard);
//...
$student->removeStudentCard($studentCard);
```

This is self explaining, the method setContact is expected to be called exaclty two times with $student as an argument for the first time, and null in the second call.

Hopefully this would be helpful for anyone looking to do something similar.

Body:
I am using Symfony and I'm trying to test the addStudentCard function in "Student" class, which adds a "StudentCard" object to $studentCards array collection propriety AND a "Student" object to $student propriety in "StudentCard" class. This is how I did it:

class StudentCard {
  private $student;
  public function getStudent();
  public function setStudent();
  //...
}

class Student {
  private $studentCards;
  public function getStudentCards();
  public function addStudentCard(StudentCard $studentCard){
    $studentCard->setStudent($this);
    $this->studentCards[] = $studentCard;
    return $this;
  //...
}

What I want to achieve is to test this addStudentCard function using a MockBuilder, I have already done this without using mocks by doing:

class StudentTest extends AbstractTestCase {
  public function testAddStudentCard(){
    $studentCard = new StudentCard();
    $student = new Student();
    $student->addStudentCard($studentCard);
    $student->assertSame($studentCard, $student->getStudentCards()[0]);
    $student->assertSame($student, $studentCard->getStudent());
}

This works as expected with no problem.

What I would like is to replace the line:

$studentCard = new StudentCard();

with something like this:

$studentCard = $this->getMockBuilder(StudentCard::class)->getMock();

But what I get is the error:
Failed asserting that null is identical to an object of class Student.

Body:
The answer Ondrej Führer provided is the right answer to the problem I described.

I had also a removeStudentCard method that deletes the student from the studentCard object, so $this->once() was not appropriate for my case. In order to test this, I did exactly the same thing Ondrej Führer suggested with some modifications, so the code line I added was:

$studentCard->expects($this->exactly(2))->method('setStudent')->withConsecutive(
    [$student],
    [null]
);
//...
$student->addStudentCard($studentCard);
//...
$student->removeStudentCard($studentCard);

This is self explaining, the method setContact is expected to be called exaclty two times with $student as an argument for the first time, and null in the second call.

Hopefully this would be helpful for anyone looking to do something similar.


来源: stackexchange

问:
Which Lisp should I learn?

Which Lisp (dialect) should I learn, and why?

The fragmentation between CL and Scheme slows uptake (at least for me!).

So, give me the "true answer", please!

I have tried to read feature comparisons, and they seem to get bogged down in esoterica (that I don't fully understand) like whether the dialect is fully tail-recursive, and the like.  I'm hoping you all (collectively) can make the opaque differences clear.

Things I like

Good library support, good environments, and Unicode support.

Things I dislike

Flamewars. Features that are useful at the beginning, but interfere with long-term learning.

Updates

I've been mostly using MzScheme, which I'm enjoying just fine, once I got readline support going.  I don't run a GUI on Unix, so it seemed to be a fine environment option for me.

I'm also very happy that Clojure has an easy to install .deb package on debian, so it's much easier to play with.  This is a big win.  Despite the hostility of some rather easy-to-anger below, low barrier to entry is a win.  I like being spoonfed.

After reading a lot more of SICP, I do understand the issues around tail recursion much better.

答:
Contra Chuck, an advantage of Common Lisp is that it has a standard that implementations stick to and strive for, such that you can develop largely with SBCL (which has excellent type checking and inference) and then, say, deploy as an executable linked with C libraries (with ECL or others) or as a .jar making use of Java libraries (with ABCL), or with a Mac or a Windows-native GUI (Clozure, both).  Common Lisp is amazingly portable across architectures and over implementations and over time, and Common Lispers make efforts to keep things this way, with the support of the language.  As an illustration, one silly divergence of unstandardized behavior is the question "is this a special variable?"  So I answered it across the implementations I use:

```<code>#-abcl
(defun special-variable-p (symbol)
  #+ecl(si:specialp symbol)
  #+ccl(proclaimed-special-p symbol)
  #+sbcl(equal '(:special t)
               (multiple-value-list-int:info :variable :kind symbol)))
</code>```

which reduces, at read time, to nothing on ABCL (it has this already), to (defun special-variable-p (symbol) (si:specialp symbol)) on ECL, and so on.  So I can put this in my .rc files and use the common function at the REPL.  But this isn't very important: this isn't threading or variously-backed networking or a Communicating Sequential Processes library.  This last example just has one #+sbcl/#-sbcl even as it runs on five implementations.  Because it relies on code that's been carefully ported.

But what permits this (and other) advantages also poses its own challenge to the learner: Common Lisp is a very big language.  It isn't something you can slurp up in a week or two, like I did Clojure (but my Clojure is already decaying with the breaking changes set to roll out - that language, although heavy with its own merits, reminded me by contrast of a lot of what I like about Common Lisp.)  So you should read a lot of this page, and keep the HyperSpec a keypress away (for me, M-x hyperspec RET do-symbols RET is sufficient nearness to the Bible.), and think about buying a few books.  I have Practical Common Lisp, just got Let Over Lambda, and will buy PAIP real soon now.

But even if Common Lisp is the True Answer, you won't completely waste your time by 'just picking' some deceptively flashy alternative (-- 'deceptive' because commonplace CL doesn't show you all that its macros can do, and it has more kinds of macros than anybody.  The usual comparison is between bad CL and syntax-optimized alternative X).  You'll still learn the basics, you can still use much of what you can read in SICP, On Lisp, The Little Schemer, etc.  A lisp, even the wrong lisp, is still better than a non-lisp.  (But you'll spend some of your time implementing parts of the right lisp, poorly, in the wrong lisp.  Meta-Greenspun.)

OwnerDisplayName: Gregg Lind

ContentLicense: CC BY-SA 3.0

Title: Which Lisp should I learn?

LastEditorDisplayName: Gregg Lind

Body:
Contra Chuck, an advantage of Common Lisp is that it has a standard that implementations stick to and strive for, such that you can develop largely with SBCL (which has excellent type checking and inference) and then, say, deploy as an executable linked with C libraries (with ECL or others) or as a .jar making use of Java libraries (with ABCL), or with a Mac or a Windows-native GUI (Clozure, both).  Common Lisp is amazingly portable across architectures and over implementations and over time, and Common Lispers make efforts to keep things this way, with the support of the language.  As an illustration, one silly divergence of unstandardized behavior is the question "is this a special variable?"  So I answered it across the implementations I use:

#-abcl
(defun special-variable-p (symbol)
  #+ecl(si:specialp symbol)
  #+ccl(proclaimed-special-p symbol)
  #+sbcl(equal '(:special t)
               (multiple-value-list-int:info :variable :kind symbol)))

which reduces, at read time, to nothing on ABCL (it has this already), to (defun special-variable-p (symbol) (si:specialp symbol)) on ECL, and so on.  So I can put this in my .rc files and use the common function at the REPL.  But this isn't very important: this isn't threading or variously-backed networking or a Communicating Sequential Processes library.  This last example just has one #+sbcl/#-sbcl even as it runs on five implementations.  Because it relies on code that's been carefully ported.

But what permits this (and other) advantages also poses its own challenge to the learner: Common Lisp is a very big language.  It isn't something you can slurp up in a week or two, like I did Clojure (but my Clojure is already decaying with the breaking changes set to roll out - that language, although heavy with its own merits, reminded me by contrast of a lot of what I like about Common Lisp.)  So you should read a lot of this page, and keep the HyperSpec a keypress away (for me, M-x hyperspec RET do-symbols RET is sufficient nearness to the Bible.), and think about buying a few books.  I have Practical Common Lisp, just got Let Over Lambda, and will buy PAIP real soon now.

But even if Common Lisp is the True Answer, you won't completely waste your time by 'just picking' some deceptively flashy alternative (-- 'deceptive' because commonplace CL doesn't show you all that its macros can do, and it has more kinds of macros than anybody.  The usual comparison is between bad CL and syntax-optimized alternative X).  You'll still learn the basics, you can still use much of what you can read in SICP, On Lisp, The Little Schemer, etc.  A lisp, even the wrong lisp, is still better than a non-lisp.  (But you'll spend some of your time implementing parts of the right lisp, poorly, in the wrong lisp.  Meta-Greenspun.)

OwnerDisplayName: ayrnieu

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: ayrnieu


问:
Avoid an extra begin block when quoting in a macro
I am writing a Julia macro like this:

```<code>macro cfunc(name, rettype)
  quotedname = Expr(:quote, name)
  return quote
    (()->ccall(($quotedname, "libc.so.6"), $rettype, ()))
  end
end
</code>```

and I am able to use it to create a function:

```<code>@cfunc(time, Int32)()  # Returns current time
</code>```

However, if I factor out the quoting macro:

```<code>macro q(name)
  sym = Expr(:quote,name)
  return quote
    $(sym)
  end
end
</code>```

macroexpand produces an extra begin and end:

```<code>:((begin
      #= REPL[142]:4 =#
      ()->begin
              #= REPL[142]:4 =#
              ccall((begin # <-- This is the extra begin
                          #= REPL[102]:4 =#
                          :clock
                      end, "libc.so.6"), Main.Int32, ())
          end       # ^^^ This is the extra end
  end)())
</code>```

which causes ccall to fail:

```<code>@cfunc(time, Int32)()
ERROR: error compiling #26: unsupported or misplaced expression "block" in function #26
Stacktrace:
 [1] top-level scope at REPL[151]:4
</code>```

How can I avoid the begin/end when quoting like this?

答:
The quote block in the q macro introduces the extra begin and end in the fully expanded version. It normally shouldn't affect the result, but ccall is special.

This works:

```<code>macro q(name)
  sym = Expr(:quote,name)
  return sym
end
</code>```

as does this quote form that does not introduce a begin/end:

```<code>macro q(name)
  sym = Expr(:quote,name)
  return :($sym)
end
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am writing a Julia macro like this:

macro cfunc(name, rettype)
  quotedname = Expr(:quote, name)
  return quote
    (()->ccall(($quotedname, "libc.so.6"), $rettype, ()))
  end
end

and I am able to use it to create a function:

@cfunc(time, Int32)()  # Returns current time

However, if I factor out the quoting macro:

macro q(name)
  sym = Expr(:quote,name)
  return quote
    $(sym)
  end
end

macroexpand produces an extra begin and end:

:((begin
      #= REPL[142]:4 =#
      ()->begin
              #= REPL[142]:4 =#
              ccall((begin # <-- This is the extra begin
                          #= REPL[102]:4 =#
                          :clock
                      end, "libc.so.6"), Main.Int32, ())
          end       # ^^^ This is the extra end
  end)())

which causes ccall to fail:

@cfunc(time, Int32)()
ERROR: error compiling #26: unsupported or misplaced expression "block" in function #26
Stacktrace:
 [1] top-level scope at REPL[151]:4

How can I avoid the begin/end when quoting like this?

Body:
The quote block in the q macro introduces the extra begin and end in the fully expanded version. It normally shouldn't affect the result, but ccall is special.

This works:

macro q(name)
  sym = Expr(:quote,name)
  return sym
end

as does this quote form that does not introduce a begin/end:

macro q(name)
  sym = Expr(:quote,name)
  return :($sym)
end


问:
R function mirroring COUNTIFS produces wrong result
the result I want to come up with has previously been dealt with already in this question: Is there an R function mirroring EXCEL COUNTIFS with date range as condition?

I've got two separate dataframes as input: TOTALREV and TOTALLISTINGS, both of which look like this in a simplified form:

```<code>TOTALREV
listing_id reviewer_id reviewer_name review_date
1       2818       10952           Lam  2009-03-30
2       2818       12798         Alice  2009-04-24
3       2818       11869       Natalja  2009-05-03
4       2818       14064       Enrique  2009-05-18
5       2818       17977       Sherwin  2009-05-25
6       2818       20192           Jie  2009-06-29
</code>```

and

```<code>TOTALLISTINGS
listing_id last_scraped.calc
1       2818        2019-03-07
2      20168        2019-03-07
3      25428        2019-03-07
4      27886        2019-03-07
5      28658        2019-03-07
6      28871        2019-03-07
</code>```

Please note that I do have multiple last_scraped.calc per listing_id

So what I actually need is a code to count all entries of review_date for which the listing_id from TOTALLISTINGS matches with the listing_id in TOTALREV and the review_datefrom TOTALREV is max 30 days from the respective last_scraped.calc in TOTALLISTINGS

Such that my intended output would be:

```<code>REVIEWCOUNT
listing_id last_scraped.calc reviews_last30
  <dbl>    <date>                   <int>
1     1   2016-11-15                   1
2     1   2016-11-20                   1
3     2   2016-11-15                   3
4     2   2016-11-20                   2
</code>```

In the previous thread "mfidino" already helped me in coming up with the following code which used to work fine until i compiled some extra data of the exact same type:

```<code>library(lubridate)
library(dplyr)

genlistings <- function(TOTALLISTINGS = NULL, TOTALREV = NULL){
      # tibble to return
      to_return <- TOTALREV %>%
        inner_join(., TOTALLISTINGS, by ='listing_id') %>%
        group_by(listing_id, last_scraped.calc) %>%
        summarise(
          reviews_last30 = sum((review_date >= (last_scraped.calc-30) & (review_date <= last_scraped.calc))))
      return(to_return)
    }

    REVIEWCOUNT <- genlistings(TOTALREV, TOTALLISTINGS)
</code>```

However when running the above code now, my R returns only the following instead of the proposed output as indicated above with REVIEWCOUNT:

```<code>head(REVIEWCOUNT)
  reviews_last30
1        1018668
</code>```

So unfortunately I think the code does not really group by listing_id or last_scraped.calc and only sum up all reviews for which the above condition is true.

Any help is much appreciated - thanks in advance!

答:
You could first merge both tables and then use table on those which are not older than 30 days to get the frequency. (I have changed max days from 30 to 3580 to get an output from your sample data.)

```<code>TOTALREV <- read.table(header=TRUE, text="listing_id reviewer_id reviewer_name review_date
1       2818       10952           Lam  2009-03-30
2       2818       12798         Alice  2009-04-24
3       2818       11869       Natalja  2009-05-03
4       2818       14064       Enrique  2009-05-18
5       2818       17977       Sherwin  2009-05-25
6       2818       20192           Jie  2009-06-29")

TOTALLISTINGS <- read.table(header=TRUE, text="listing_id last_scraped.calc
1       2818        2019-03-07
2      20168        2019-03-07
3      25428        2019-03-07
4      27886        2019-03-07
5      28658        2019-03-07
6      28871        2019-03-07")

#Change to Date to allow calculating difference
TOTALREV$review_date <- as.Date(TOTALREV$review_date)
TOTALLISTINGS$last_scraped.calc <- as.Date(TOTALLISTINGS$last_scraped.calc)

me <- merge(TOTALREV, TOTALLISTINGS,)
#maxDays <- 30
maxDays <- 3580
data.frame(with(me[me$review_date - me$last_scraped.calc <= 0 & me$review_date - me$last_scraped.calc >= -maxDays,], table(listing_id, last_scraped.calc)))
#  listing_id last_scraped.calc Freq
#1       2818        2019-03-07    3
</code>```

Body:
the result I want to come up with has previously been dealt with already in this question: Is there an R function mirroring EXCEL COUNTIFS with date range as condition?

I've got two separate dataframes as input: TOTALREV and TOTALLISTINGS, both of which look like this in a simplified form:

TOTALREV
listing_id reviewer_id reviewer_name review_date
1       2818       10952           Lam  2009-03-30
2       2818       12798         Alice  2009-04-24
3       2818       11869       Natalja  2009-05-03
4       2818       14064       Enrique  2009-05-18
5       2818       17977       Sherwin  2009-05-25
6       2818       20192           Jie  2009-06-29

and

TOTALLISTINGS
listing_id last_scraped.calc
1       2818        2019-03-07
2      20168        2019-03-07
3      25428        2019-03-07
4      27886        2019-03-07
5      28658        2019-03-07
6      28871        2019-03-07

Please note that I do have multiple last_scraped.calc per listing_id

So what I actually need is a code to count all entries of review_date for which the listing_id from TOTALLISTINGS matches with the listing_id in TOTALREV and the review_datefrom TOTALREV is max 30 days from the respective last_scraped.calc in TOTALLISTINGS

Such that my intended output would be:

REVIEWCOUNT
listing_id last_scraped.calc reviews_last30
  <dbl>    <date>                   <int>
1     1   2016-11-15                   1
2     1   2016-11-20                   1
3     2   2016-11-15                   3
4     2   2016-11-20                   2

In the previous thread "mfidino" already helped me in coming up with the following code which used to work fine until i compiled some extra data of the exact same type:

library(lubridate)
library(dplyr)

genlistings <- function(TOTALLISTINGS = NULL, TOTALREV = NULL){
      # tibble to return
      to_return <- TOTALREV %>%
        inner_join(., TOTALLISTINGS, by ='listing_id') %>%
        group_by(listing_id, last_scraped.calc) %>%
        summarise(
          reviews_last30 = sum((review_date >= (last_scraped.calc-30) & (review_date <= last_scraped.calc))))
      return(to_return)
    }

    REVIEWCOUNT <- genlistings(TOTALREV, TOTALLISTINGS)

However when running the above code now, my R returns only the following instead of the proposed output as indicated above with REVIEWCOUNT:

head(REVIEWCOUNT)
  reviews_last30
1        1018668

So unfortunately I think the code does not really group by listing_id or last_scraped.calc and only sum up all reviews for which the above condition is true.

Any help is much appreciated - thanks in advance!

Body:
You could first merge both tables and then use table on those which are not older than 30 days to get the frequency. (I have changed max days from 30 to 3580 to get an output from your sample data.)

TOTALREV <- read.table(header=TRUE, text="listing_id reviewer_id reviewer_name review_date
1       2818       10952           Lam  2009-03-30
2       2818       12798         Alice  2009-04-24
3       2818       11869       Natalja  2009-05-03
4       2818       14064       Enrique  2009-05-18
5       2818       17977       Sherwin  2009-05-25
6       2818       20192           Jie  2009-06-29")

TOTALLISTINGS <- read.table(header=TRUE, text="listing_id last_scraped.calc
1       2818        2019-03-07
2      20168        2019-03-07
3      25428        2019-03-07
4      27886        2019-03-07
5      28658        2019-03-07
6      28871        2019-03-07")

#Change to Date to allow calculating difference
TOTALREV$review_date <- as.Date(TOTALREV$review_date)
TOTALLISTINGS$last_scraped.calc <- as.Date(TOTALLISTINGS$last_scraped.calc)

me <- merge(TOTALREV, TOTALLISTINGS,)
#maxDays <- 30
maxDays <- 3580
data.frame(with(me[me$review_date - me$last_scraped.calc <= 0 & me$review_date - me$last_scraped.calc >= -maxDays,], table(listing_id, last_scraped.calc)))
#  listing_id last_scraped.calc Freq
#1       2818        2019-03-07    3


问:
OpenJFX application fails to launch using Scala
Launching following application fails with java.lang.NoSuchMethodException: dev.buildingdragons.dragon.Dragon$.<init>() (find the full stack trace below).

To me, it looks like there is a constructor missing, but which? And Why?

I do now there are projects like ScalaFX but before using them I want to fully understand what is going on so I really want to create a walking skeleton.

Environment:

Windows 10 Professional

IntelliJ IDEA Ultimate 2019.1.2

OpenJDK 64-Bit Server VM Zulu11.2+3 (build 11.0.1+13-LTS, mixed mode)

Dragon.scala:

```<code>package dev.buildingdragons.dragon

import javafx.application.{Application, Platform}
import javafx.scene.Scene
import javafx.scene.control.Button
import javafx.stage.Stage

object Dragon extends Application {
  def main(args: Array[String]) = Application.launch(args: _*)

  override def start(stage: Stage): Unit = {
    val scene = new Scene(new Button("Test"))

    stage.setTitle("Hello, Dragon!")
    stage.setScene(scene)
    stage.showAndWait()

    Platform.exit()
  }
}
</code>```

build.gradle:

```<code>plugins {
    id 'scala'
    id 'org.openjfx.javafxplugin' version '0.0.7'
}

compileScala.targetCompatibility = 1.8

// In this section you declare where to find the dependencies of your project
repositories {
    mavenCentral()
}

dependencies {
    compile 'org.scala-lang:scala-library:2.12.8'
    compile 'org.scalafx:scalafx_2.12:11-R16'
}

javafx {
    version = "11.0.2"
    modules = ['javafx.controls']
}
</code>```

Full stack trace:

```<code>Exception in Application constructor
Exception in thread "main" java.lang.RuntimeException: Unable to construct Application instance: class dev.buildingdragons.dragon.Dragon$
    at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:890)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:195)
    at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.lang.NoSuchMethodException: dev.buildingdragons.dragon.Dragon$.<init>()
    at java.base/java.lang.Class.getConstructor0(Class.java:3350)
    at java.base/java.lang.Class.getConstructor(Class.java:2152)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$8(LauncherImpl.java:801)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:455)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:428)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:427)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:174)
    ... 1 more
</code>```

EDIT: As suggested by eugene-ryzhikov I modified Dragon.scala:

```<code>package dev.buildingdragons.dragon

import javafx.application.{Application, Platform}
import javafx.scene.Scene
import javafx.scene.control.Button
import javafx.stage.Stage

class Dragon extends Application {
  override def start(stage: Stage): Unit = {
    val scene = new Scene(new Button("Test"))

    stage.setTitle("Hello, Dragon!")
    stage.setScene(scene)
    stage.showAndWait()

    Platform.exit()
  }
}

object Dragon {
  def main(args: Array[String]) = Application.launch(classOf[Dragon],  args: _*)
}
</code>```

That solved the original problem but now I ran into the problem I was afraid of: Java's Project Jigsaw:

```<code>Exception in Application start method
java.lang.reflect.InvocationTargetException
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:464)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:363)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1051)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:900)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:195)
    at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.lang.IllegalAccessError: superclass access check failed: class com.sun.javafx.scene.control.ControlHelper (in unnamed module @0x4e08e183) cannot access class com.sun.javafx.scene.layout.RegionHelper (in module javafx.graphics) because module javafx.graphics does not export com.sun.javafx.scene.layout to unnamed module @0x4e08e183
    at java.base/java.lang.ClassLoader.defineClass1(Native Method)
    at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1016)
    at java.base/java.security.SecureClassLoader.defineClass(SecureClassLoader.java:174)
    at java.base/jdk.internal.loader.BuiltinClassLoader.defineClass(BuiltinClassLoader.java:802)
    at java.base/jdk.internal.loader.BuiltinClassLoader.findClassOnClassPathOrNull(BuiltinClassLoader.java:700)
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClassOrNull(BuiltinClassLoader.java:623)
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
    at javafx.scene.control.Control.<clinit>(Control.java:86)
    at dev.buildingdragons.dragon.Dragon.start(Dragon.scala:10)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:846)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:455)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:428)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:427)
    at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
    at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:174)
    ... 1 more
Exception running application dev.buildingdragons.dragon.Dragon
</code>```

I believe that is due to the fact that Scala does not enforce module restrictions at compile time but the JVM does at runtime.

答: That error is the consequence of having your start method within the object. Move it to the new Dragon class with main method in the companion Dragon object. Also use the launch method where you can pass the application class.

Body:
Launching following application fails with java.lang.NoSuchMethodException: dev.buildingdragons.dragon.Dragon$.<init>() (find the full stack trace below).

To me, it looks like there is a constructor missing, but which? And Why?

I do now there are projects like ScalaFX but before using them I want to fully understand what is going on so I really want to create a walking skeleton.

Environment:

Windows 10 Professional

IntelliJ IDEA Ultimate 2019.1.2

OpenJDK 64-Bit Server VM Zulu11.2+3 (build 11.0.1+13-LTS, mixed mode)

Dragon.scala:

package dev.buildingdragons.dragon

import javafx.application.{Application, Platform}
import javafx.scene.Scene
import javafx.scene.control.Button
import javafx.stage.Stage

object Dragon extends Application {
  def main(args: Array[String]) = Application.launch(args: _*)

  override def start(stage: Stage): Unit = {
    val scene = new Scene(new Button("Test"))

    stage.setTitle("Hello, Dragon!")
    stage.setScene(scene)
    stage.showAndWait()

    Platform.exit()
  }
}

build.gradle:

plugins {
    id 'scala'
    id 'org.openjfx.javafxplugin' version '0.0.7'
}

compileScala.targetCompatibility = 1.8

// In this section you declare where to find the dependencies of your project
repositories {
    mavenCentral()
}

dependencies {
    compile 'org.scala-lang:scala-library:2.12.8'
    compile 'org.scalafx:scalafx_2.12:11-R16'
}

javafx {
    version = "11.0.2"
    modules = ['javafx.controls']
}

Full stack trace:

Exception in Application constructor
Exception in thread "main" java.lang.RuntimeException: Unable to construct Application instance: class dev.buildingdragons.dragon.Dragon$
    at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:890)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:195)
    at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.lang.NoSuchMethodException: dev.buildingdragons.dragon.Dragon$.<init>()
    at java.base/java.lang.Class.getConstructor0(Class.java:3350)
    at java.base/java.lang.Class.getConstructor(Class.java:2152)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$8(LauncherImpl.java:801)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:455)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:428)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:427)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:174)
    ... 1 more

EDIT: As suggested by eugene-ryzhikov I modified Dragon.scala:

package dev.buildingdragons.dragon

import javafx.application.{Application, Platform}
import javafx.scene.Scene
import javafx.scene.control.Button
import javafx.stage.Stage

class Dragon extends Application {
  override def start(stage: Stage): Unit = {
    val scene = new Scene(new Button("Test"))

    stage.setTitle("Hello, Dragon!")
    stage.setScene(scene)
    stage.showAndWait()

    Platform.exit()
  }
}

object Dragon {
  def main(args: Array[String]) = Application.launch(classOf[Dragon],  args: _*)
}

That solved the original problem but now I ran into the problem I was afraid of: Java's Project Jigsaw:

Exception in Application start method
java.lang.reflect.InvocationTargetException
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:464)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:363)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1051)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:900)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:195)
    at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.lang.IllegalAccessError: superclass access check failed: class com.sun.javafx.scene.control.ControlHelper (in unnamed module @0x4e08e183) cannot access class com.sun.javafx.scene.layout.RegionHelper (in module javafx.graphics) because module javafx.graphics does not export com.sun.javafx.scene.layout to unnamed module @0x4e08e183
    at java.base/java.lang.ClassLoader.defineClass1(Native Method)
    at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1016)
    at java.base/java.security.SecureClassLoader.defineClass(SecureClassLoader.java:174)
    at java.base/jdk.internal.loader.BuiltinClassLoader.defineClass(BuiltinClassLoader.java:802)
    at java.base/jdk.internal.loader.BuiltinClassLoader.findClassOnClassPathOrNull(BuiltinClassLoader.java:700)
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClassOrNull(BuiltinClassLoader.java:623)
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
    at javafx.scene.control.Control.<clinit>(Control.java:86)
    at dev.buildingdragons.dragon.Dragon.start(Dragon.scala:10)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:846)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:455)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:428)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:427)
    at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
    at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:174)
    ... 1 more
Exception running application dev.buildingdragons.dragon.Dragon

I believe that is due to the fact that Scala does not enforce module restrictions at compile time but the JVM does at runtime.


问:
How can I close a dropdown on click outside?
I would like to close my login menu dropdown when the user click anywhere outside of that dropdown, and I'd like to do that with Angular2 and with the Angular2 "approach"...

I have implemented a solution, but I really do not feel confident with it. I think there must be an easiest way to achieve the same result, so if you have any ideas ... let's discuss :) !

Here is my implementation:

The dropdown component:

This is the component for my dropdown:

Every time this component it set to visible, (For example: when the user click on a button to display it) it subscribe to a "global" rxjs subject userMenu stored within the SubjectsService.

And every time it is hidden, it unsubscribe to this subject.

Every click anywhere within the template of this component trigger the onClick() method, which just stop event bubbling to the top (and the application component)

Here is the code

```<code>export class UserMenuComponent {

    _isVisible: boolean = false;
    _subscriptions: Subscription<any> = null;

    constructor(public subjects: SubjectsService) {
    }

    onClick(event) {
        event.stopPropagation();
    }

    set isVisible(v) {
        if( v ){
            setTimeout( () => {
this._subscriptions =  this.subjects.userMenu.subscribe((e) => {
                       this.isVisible = false;
                       })
            }, 0);
        } else {
            this._subscriptions.unsubscribe();
        }
        this._isVisible = v;
    }

    get isVisible() {
        return this._isVisible;
    }
}
</code>```

The application component:

On the other hand, there is the application component (which is a parent of the dropdown component):

This component catch every click event and emit on the same rxjs Subject (userMenu)

Here is the code:

```<code>export class AppComponent {

    constructor( public subjects: SubjectsService) {
        document.addEventListener('click', () => this.onClick());
    }
    onClick( ) {
        this.subjects.userMenu.next({});
    }
}
</code>```

What bother me:

I do not feel really comfortable with the idea of having a global Subject that act as the connector between those components.

The setTimeout: This is needed because here is what happen otherwise if the user click on the button that show the dropdown:

The user click on the button (which is not a part of the dropdown component) to show the dropdown.

The dropdown is displayed and it immediately subscribe to the userMenu subject.

The click event bubble up to the app component and gets caught

The application component emit an event on the userMenu subject

The dropdown component catch this action on userMenu and hide the dropdown.

At the end the dropdown is never displayed.

This set timeout delay the subscription to the end of the current JavaScript code turn which solve the problem, but in a very in elegant way in my opinion.

If you know cleaner, better, smarter, faster or stronger solutions, please let me know :) !

答:
THE MOST ELEGANT METHOD :D

There is one easiest way to do that, no need any directives for that.

"element-that-toggle-your-dropdown" should be button tag. Use any method in (blur) attribute. That's all.

```<code><button class="element-that-toggle-your-dropdown"
               (blur)="isDropdownOpen = false"
               (click)="isDropdownOpen = !isDropdownOpen">
</button>
</code>```

Body:
I would like to close my login menu dropdown when the user click anywhere outside of that dropdown, and I'd like to do that with Angular2 and with the Angular2 "approach"...

I have implemented a solution, but I really do not feel confident with it. I think there must be an easiest way to achieve the same result, so if you have any ideas ... let's discuss :) !

Here is my implementation:

The dropdown component:

This is the component for my dropdown:

Every time this component it set to visible, (For example: when the user click on a button to display it) it subscribe to a "global" rxjs subject userMenu stored within the SubjectsService.

And every time it is hidden, it unsubscribe to this subject.

Every click anywhere within the template of this component trigger the onClick() method, which just stop event bubbling to the top (and the application component)

Here is the code

export class UserMenuComponent {

    _isVisible: boolean = false;
    _subscriptions: Subscription<any> = null;

    constructor(public subjects: SubjectsService) {
    }

    onClick(event) {
        event.stopPropagation();
    }

    set isVisible(v) {
        if( v ){
            setTimeout( () => {
this._subscriptions =  this.subjects.userMenu.subscribe((e) => {
                       this.isVisible = false;
                       })
            }, 0);
        } else {
            this._subscriptions.unsubscribe();
        }
        this._isVisible = v;
    }

    get isVisible() {
        return this._isVisible;
    }
}

The application component:

On the other hand, there is the application component (which is a parent of the dropdown component):

This component catch every click event and emit on the same rxjs Subject (userMenu)

Here is the code:

export class AppComponent {

    constructor( public subjects: SubjectsService) {
        document.addEventListener('click', () => this.onClick());
    }
    onClick( ) {
        this.subjects.userMenu.next({});
    }
}

What bother me:

I do not feel really comfortable with the idea of having a global Subject that act as the connector between those components.

The setTimeout: This is needed because here is what happen otherwise if the user click on the button that show the dropdown:

The user click on the button (which is not a part of the dropdown component) to show the dropdown.

The dropdown is displayed and it immediately subscribe to the userMenu subject.

The click event bubble up to the app component and gets caught

The application component emit an event on the userMenu subject

The dropdown component catch this action on userMenu and hide the dropdown.

At the end the dropdown is never displayed.

This set timeout delay the subscription to the end of the current JavaScript code turn which solve the problem, but in a very in elegant way in my opinion.

If you know cleaner, better, smarter, faster or stronger solutions, please let me know :) !

Body:
THE MOST ELEGANT METHOD :D

There is one easiest way to do that, no need any directives for that.

"element-that-toggle-your-dropdown" should be button tag. Use any method in (blur) attribute. That's all.

<button class="element-that-toggle-your-dropdown"
               (blur)="isDropdownOpen = false"
               (click)="isDropdownOpen = !isDropdownOpen">
</button>


问:
What is the use of overriding the finalize() method of Object class?
As far as I know , in java if we want to manually call the garbage collector we can do System.gc().

1.What are the operations that we do inside our overriden finalize() method?

2.Is it required to override the finalize() method if we want to manually call the JVM garbage collector?

答:
What are the operations that we do inside our overriden finalize() method?

Free memory alocated manually (through some native calls) i.e. not managed by GC. It is a really rare situation.
Some people put there also a check, that other resources connected with the object have already been released - but it's only for debugging purposes and it's not very reliable.

You must remember that:

finalize is about memory and only memory.

You have no control when it will be invoked and even whether it be invoked.

So never ever put there releasing any other resources (like file handles, locks). All those resources must be released manually.

And overriding finalize has nothing to do with calling System.gc().


问:
Python to return specific column using list comprehension or apply()
I'm trying to convert R code to Python code and stuck at this point. Can you tell me what is the best way to implement this code snippet in Python?

```<code>only0_0$count =0
for(i in 2:length(only0_0$ID))
{
    only0_0$count[i]=ifelse((only0_0$year[i]-1) %in%
    clientData$Year[clientData$CUSTOMERID %in% only0_0$ID[i]],1,0)
}
</code>```

Background:

Both clientData and only0_0 are DataFrames.

Client Data{columns: year, CustomerID, ...}

only0_0 {columns: year, ID}

ID and CustomerID both represents same thing and are not unique in the corresponding table.

Sort only0_0 by {'ID','year'}

PseudoCode:

In only0_0, create new column 'count' will all zeros.

for loop starting from second observation to last, populate 'count' variable as:

select all 'CustomerID' from clientData where 'ID' in only0_0 matches for a particular row.

e.g. only0_0.ID == 3197

clientData.CustomerID will return all rows id's with customerID=3197

e.g output of last step: rowid(or index in Python) {3,11, 81, 87}

extract corresponding year values from rows id's returned from last step

e.g. output of last step: {2006, 2008, 2009, 2006}

let's say: output of (only0_0.year - 1) == 2008

since 2008 is in {2006, 2008, 2009, 2006}, count = 1

Let me know if it's clear now.

答:
Thanks, I got the answer. </p>

```<code>    if ((only0_0.year[i] - 1) in (clientData['Year'][clientData['CUSTOMERID_transformed'] == only0_0.loc[i, 'ID0_0']].values)):
        only0_0.loc[i,"count"]=1
    else:
        only0_0.loc[i,"count"]=0
</code>```

Body:
I'm trying to convert R code to Python code and stuck at this point. Can you tell me what is the best way to implement this code snippet in Python?

only0_0$count =0
for(i in 2:length(only0_0$ID))
{
    only0_0$count[i]=ifelse((only0_0$year[i]-1) %in%
    clientData$Year[clientData$CUSTOMERID %in% only0_0$ID[i]],1,0)
}

Background:

Both clientData and only0_0 are DataFrames.

Client Data{columns: year, CustomerID, ...}

only0_0 {columns: year, ID}

ID and CustomerID both represents same thing and are not unique in the corresponding table.

Sort only0_0 by {'ID','year'}

PseudoCode:

In only0_0, create new column 'count' will all zeros.

for loop starting from second observation to last, populate 'count' variable as:

select all 'CustomerID' from clientData where 'ID' in only0_0 matches for a particular row.

e.g. only0_0.ID == 3197

clientData.CustomerID will return all rows id's with customerID=3197

e.g output of last step: rowid(or index in Python) {3,11, 81, 87}

extract corresponding year values from rows id's returned from last step

e.g. output of last step: {2006, 2008, 2009, 2006}

let's say: output of (only0_0.year - 1) == 2008

since 2008 is in {2006, 2008, 2009, 2006}, count = 1

Let me know if it's clear now.

Body:
Thanks, I got the answer.

    if ((only0_0.year[i] - 1) in (clientData['Year'][clientData['CUSTOMERID_transformed'] == only0_0.loc[i, 'ID0_0']].values)):
        only0_0.loc[i,"count"]=1
    else:
        only0_0.loc[i,"count"]=0


问:
Using Lodash to find a partial string in any property value of an object
I want to use Lodash to return true when an object contains in any of its values, a match for a partial string. I've tried this with _.includes as follows.

```<code>const ob = {first: "Fred", last: "Flintstone",}
const search = "stone";
const result = _.includes(ob, search)
console.log(result); // false
</code>```

I've also tried this using a regular expression instead of a string for the search term.

```<code>const search = /stone/gi;
</code>```

Both times result returns false. I want result to return true. How can I do this in Lodash?

答:
You could use _filter if you want to use lodash.</p>

```<code>const ob = {first: "Fred", last: "Flintstone",}
var filteredOb = _.filter(ob, function(elem) {
    return elem.indexOf("stone") > -1;
});
console.log(filteredOb);
</code>```

Body:
I want to use Lodash to return true when an object contains in any of its values, a match for a partial string. I've tried this with _.includes as follows.

const ob = {first: "Fred", last: "Flintstone",}
const search = "stone";
const result = _.includes(ob, search)
console.log(result); // false

I've also tried this using a regular expression instead of a string for the search term.

const search = /stone/gi;

Both times result returns false. I want result to return true. How can I do this in Lodash?

Body:
You could use _filter if you want to use lodash.

const ob = {first: "Fred", last: "Flintstone",}
var filteredOb = _.filter(ob, function(elem) {
    return elem.indexOf("stone") > -1;
});
console.log(filteredOb);


问:
Thymeleaf: Get href without application context path
How to get URL without context path?
I am using spring boot 1.5.18.RELEASE and Thymeleaf

I tried this two possibilities.

```<code><a th:href="@{${website}}" target="_blank"> Click here </a>

<a th:href="${website}" target="_blank"> Click here </a>
</code>```

For example if the ${website} has the value www.example.com I get this result:

http://localhost:8081/MyApp/www.example.com
but I would like to get only this www.example.com  without context Path.

答:
If you are linking to an external site, you should have http:// or https:// as part of the link -- https://www.example.com rather than just www.example.com.  once you've added that, either of the two solutions in your initial post will work.

```<code><a th:href="@{${website}}" target="_blank">Click here</a>
<a th:href="${website}" target="_blank">Click here</a>
</code>```

// as you've indicated will work as well, but it's a bit silly.  That just means that if your site is https:// it the link will be https:// (and vice versa for http://).

If you don't want to add https:// to your link, I would recommend something like this:

```<code><a th:href="|https://${website}|" target="_blank">> Click here</a>
</code>```

Body:
How to get URL without context path?
I am using spring boot 1.5.18.RELEASE and Thymeleaf

I tried this two possibilities.

 Click here

 Click here

For example if the ${website} has the value www.example.com I get this result:

http://localhost:8081/MyApp/www.example.com
but I would like to get only this www.example.com  without context Path.

Body:
If you are linking to an external site, you should have http:// or https:// as part of the link -- https://www.example.com rather than just www.example.com.  once you've added that, either of the two solutions in your initial post will work.

<a th:href="@{${website}}" target="_blank">Click here</a>
<a th:href="${website}" target="_blank">Click here</a>

// as you've indicated will work as well, but it's a bit silly.  That just means that if your site is https:// it the link will be https:// (and vice versa for http://).

If you don't want to add https:// to your link, I would recommend something like this:

<a th:href="|https://${website}|" target="_blank">&gt; Click here</a>


问:
Mutliple Python installs necessary?
So I've read this thread
python location on mac osx

but still a couple questions

running

```<code>$ which -a python python3
</code>```

returns

```<code>/Library/Frameworks/Python.framework/Versions/2.7/bin/python
/usr/local/bin/python
/usr/bin/python
</code>```

and just

```<code>$which python
</code>```

returns

```<code>/Library/Frameworks/Python.framework/Versions/2.7/bin/python
</code>```

And I also have Python installed here which isn't on my PATH

```<code>/Users/foo/Library/Python/2.7/bin
</code>```

Does this mean I can safely delete ALL python binaries except for the one returned by the which Python command?
I just don't understand the necessity of multiple Python installs if you don't need multiple versions.

答:
Do not delete the default python installation that comes with the OS, you will break your system, that Pythons are necessary for the right functionality of the OS, don't mess with them, if you want to develop your own projects, better use pyenv (https://github.com/pyenv/pyenv) or similar tools to manage independent Python installations and/or versions, also to manage a virtual environment.

Never touch pre-installed binaries, unless you want to break your system.

Title: Mutliple Python installs necessary?

Body:
So I've read this thread
python location on mac osx

but still a couple questions

running

$ which -a python python3

returns

/Library/Frameworks/Python.framework/Versions/2.7/bin/python
/usr/local/bin/python
/usr/bin/python

and just

$which python

returns

/Library/Frameworks/Python.framework/Versions/2.7/bin/python

And I also have Python installed here which isn't on my PATH

/Users/foo/Library/Python/2.7/bin

Does this mean I can safely delete ALL python binaries except for the one returned by the which Python command?
I just don't understand the necessity of multiple Python installs if you don't need multiple versions.


问:
Error with RecyclerView: No adapter attached; skipping layout
I can't get my code work
I'm trying to get a list of my database activities.

A lot of research here and none of the answers helped me

My Adapter

```<code>public class AtividadesAdapter extends RecyclerView.Adapter<AtividadesAdapter.AtividadesViewHolder> {

    private Context mCtx;
    private List<Atividades> atividadesList;

    public AtividadesAdapter(Context mCtx, List<Atividades> atividadesList) {
        this.mCtx = mCtx;
        this.atividadesList = atividadesList;
    }

    @Override
    public AtividadesViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(mCtx);
        View view = inflater.inflate(R.layout.atividades_lista, null);
        return new AtividadesViewHolder(view);
    }

    @Override
    public void onBindViewHolder(AtividadesViewHolder holder, int position) {
        Atividades atividades = atividadesList.get(position);
        holder.textViewAtividade.setText(atividades.getAtividade());
        holder.textViewData.setText(String.valueOf(atividades.getDataPrevista()));
        holder.textViewHora.setText(String.valueOf(atividades.getHora()));
        holder.textViewDestinatarios.setText(atividades.getDestinatarios());
    }

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

    class AtividadesViewHolder extends RecyclerView.ViewHolder {

        TextView textViewAtividade, textViewData, textViewHora, textViewDestinatarios;

        public AtividadesViewHolder(View itemView) {
            super(itemView);
            textViewAtividade = itemView.findViewById(R.id.textViewAtividade);
            textViewData = itemView.findViewById(R.id.textViewData);
            textViewHora = itemView.findViewById(R.id.textViewHora);
            textViewDestinatarios = itemView.findViewById(R.id.textViewDestinatarios);
        }
    }
}
</code>```

My activity

```<code>public class AtividadesActivity extends AppCompatActivity {

private static final String URL_ATIVIDADES = "";
List<Atividades> atividadesList = new ArrayList<>();
public RecyclerView recyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.atividadesrecyclerview);
        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setHasFixedSize(true);
        loadAtividades();
    }

    private void loadAtividades() {
        StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_ATIVIDADES,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONArray array = new JSONArray(response);
                            for (int i = 0; i < array.length(); i++) {
                                JSONObject a = array.getJSONObject(i);
                                Log.d("Valores", a.getString("Atividade"));
                                atividadesList.add(new Atividades(
                                        a.getInt("idAtividade"),
                                        a.getString("Atividade"),
                                        java.sql.Date.valueOf(a.getString("dataPrevista")),
                                        java.sql.Time.valueOf(a.getString("hora")),
                                        a.getString("Destinatarios"),
                                        a.getString("Local")
                                ));
                            }
                            AtividadesAdapter mAdapter = new AtividadesAdapter(AtividadesActivity.this, atividadesList);
                            recyclerView.setAdapter(mAdapter);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });
        Volley.newRequestQueue(this).add(stringRequest);
    }
}
</code>```

Everytime i'm trying to start the app, i get this error.
I have already change the xml files to match with the examples provided here but still have no success.

答:
Based on your question and the code I think this will help you.</p>

```<code>@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.atividadesrecyclerview);
        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setHasFixedSize(true);
        AtividadesAdapter mAdapter = new AtividadesAdapter(getApplicationContext, atividadesList);
         recyclerView.setAdapter(mAdapter);
        loadAtividades();
}
</code>```

Body:
I can't get my code work
I'm trying to get a list of my database activities.

A lot of research here and none of the answers helped me

My Adapter

public class AtividadesAdapter extends RecyclerView.Adapter<AtividadesAdapter.AtividadesViewHolder> {

    private Context mCtx;
    private List<Atividades> atividadesList;

    public AtividadesAdapter(Context mCtx, List<Atividades> atividadesList) {
        this.mCtx = mCtx;
        this.atividadesList = atividadesList;
    }

    @Override
    public AtividadesViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(mCtx);
        View view = inflater.inflate(R.layout.atividades_lista, null);
        return new AtividadesViewHolder(view);
    }

    @Override
    public void onBindViewHolder(AtividadesViewHolder holder, int position) {
        Atividades atividades = atividadesList.get(position);
        holder.textViewAtividade.setText(atividades.getAtividade());
        holder.textViewData.setText(String.valueOf(atividades.getDataPrevista()));
        holder.textViewHora.setText(String.valueOf(atividades.getHora()));
        holder.textViewDestinatarios.setText(atividades.getDestinatarios());
    }

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

    class AtividadesViewHolder extends RecyclerView.ViewHolder {

        TextView textViewAtividade, textViewData, textViewHora, textViewDestinatarios;

        public AtividadesViewHolder(View itemView) {
            super(itemView);
            textViewAtividade = itemView.findViewById(R.id.textViewAtividade);
            textViewData = itemView.findViewById(R.id.textViewData);
            textViewHora = itemView.findViewById(R.id.textViewHora);
            textViewDestinatarios = itemView.findViewById(R.id.textViewDestinatarios);
        }
    }
}

My activity

public class AtividadesActivity extends AppCompatActivity {

private static final String URL_ATIVIDADES = "";
List<Atividades> atividadesList = new ArrayList<>();
public RecyclerView recyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.atividadesrecyclerview);
        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setHasFixedSize(true);
        loadAtividades();
    }

    private void loadAtividades() {
        StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_ATIVIDADES,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONArray array = new JSONArray(response);
                            for (int i = 0; i < array.length(); i++) {
                                JSONObject a = array.getJSONObject(i);
                                Log.d("Valores", a.getString("Atividade"));
                                atividadesList.add(new Atividades(
                                        a.getInt("idAtividade"),
                                        a.getString("Atividade"),
                                        java.sql.Date.valueOf(a.getString("dataPrevista")),
                                        java.sql.Time.valueOf(a.getString("hora")),
                                        a.getString("Destinatarios"),
                                        a.getString("Local")
                                ));
                            }
                            AtividadesAdapter mAdapter = new AtividadesAdapter(AtividadesActivity.this, atividadesList);
                            recyclerView.setAdapter(mAdapter);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });
        Volley.newRequestQueue(this).add(stringRequest);
    }
}

Everytime i'm trying to start the app, i get this error.
I have already change the xml files to match with the examples provided here but still have no success.

Body:
Based on your question and the code I think this will help you.

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.atividadesrecyclerview);
        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setHasFixedSize(true);
        AtividadesAdapter mAdapter = new AtividadesAdapter(getApplicationContext, atividadesList);
         recyclerView.setAdapter(mAdapter);
        loadAtividades();
}


问:
PDO with parameter
I would like to have various option to change $this_var that contain different fieldname
such as 'apple'=1 or 'orange'=1, is it possible?</p>

```<code>$statement->prepare(SELECT * table WHERE $this_var = 1);
</code>```

答: No, you cannot have prepared statements with variable field names. </p>

Title: PDO with parameter

Body:
I would like to have various option to change $this_var that contain different fieldname
such as 'apple'=1 or 'orange'=1, is it possible?

$statement->prepare(SELECT * table WHERE $this_var = 1);


问:
Which Spring Cloud Zuul timeout property to use when using the default setup?
I'm setting up a (Spring boot 2) Spring cloud zuul/gateway and ran into timeout issues. After reading the official docs and checking a similar question, I'm not convinced about the proposed solution.

I use the following type of route configuration:

```<code>routes:
 test-service:
  path: /test-service/**
  serviceId: test-service
</code>```

which I believe to not be "url routes", so I think these properties do not apply:

```<code>zuul.host.connect-timeout-millis
zuul.host.connection-request-timeout-millis
zuul.host.socket-timeout-millis
</code>```

I tried setting the properties below, but IntelliJ indicates these properties "do not exist". Is this a quirk in the IDE, or are these properties only present/active under certain circumstances?

```<code>hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds= 11000
hystrix.command.default.execution.timeout.enabled=false
ribbon.ConnectTimeout= 10000
ribbon.ReadTimeout: 10000
</code>```

E.g. see this screenshot from my bootstrap.yml, where it only suggests other properties:

Is Ribbon and hystrix present and active by default with this maven dependency?

```<code><dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>
</code>```

答:
If you want to configure timeout in Zuul you have two options ,

If you have configured Zuul to use  service discovery, you need to configure these timeouts with the below  Ribbon properties

```<code>ribbon.ReadTimeout
ribbon.SocketTimeout
</code>```

If you have configured Zuul routes by specifying URLs then use below properties ,as per your configuration you need to use this one

```<code>zuul.host.connect-timeout-millis
zuul.host.socket-timeout-millis
</code>```

Offical doc is here (Look into Zuul Timeouts section)

https://cloud.spring.io/spring-cloud-netflix/multi/multi__router_and_filter_zuul.html

Below will show how they  work with Hystrix,

https://cloud.spring.io/spring-cloud-static/Edgware.SR3/single/spring-cloud.html#_service_discovery_configuration

Note : Properties are case sensitive

I tried setting the properties below, but IntelliJ indicates these
  properties "do not exist". Is this a quirk in the IDE, or are these
  properties only present/active under certain circumstances?

May be quirk in the IDE.We have official doc that says the property exits.

Body:
I'm setting up a (Spring boot 2) Spring cloud zuul/gateway and ran into timeout issues. After reading the official docs and checking a similar question, I'm not convinced about the proposed solution.

I use the following type of route configuration:

routes:
 test-service:
  path: /test-service/**
  serviceId: test-service

which I believe to not be "url routes", so I think these properties do not apply:

zuul.host.connect-timeout-millis
zuul.host.connection-request-timeout-millis
zuul.host.socket-timeout-millis

I tried setting the properties below, but IntelliJ indicates these properties "do not exist". Is this a quirk in the IDE, or are these properties only present/active under certain circumstances?

hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds= 11000
hystrix.command.default.execution.timeout.enabled=false
ribbon.ConnectTimeout= 10000
ribbon.ReadTimeout: 10000

E.g. see this screenshot from my bootstrap.yml, where it only suggests other properties:

Is Ribbon and hystrix present and active by default with this maven dependency?

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>

Body:
If you want to configure timeout in Zuul you have two options ,

If you have configured Zuul to use  service discovery, you need to configure these timeouts with the below  Ribbon properties

ribbon.ReadTimeout
ribbon.SocketTimeout

If you have configured Zuul routes by specifying URLs then use below properties ,as per your configuration you need to use this one

zuul.host.connect-timeout-millis
zuul.host.socket-timeout-millis

Offical doc is here (Look into Zuul Timeouts section)

https://cloud.spring.io/spring-cloud-netflix/multi/multi__router_and_filter_zuul.html

Below will show how they  work with Hystrix,

https://cloud.spring.io/spring-cloud-static/Edgware.SR3/single/spring-cloud.html#_service_discovery_configuration

Note : Properties are case sensitive

I tried setting the properties below, but IntelliJ indicates these
  properties "do not exist". Is this a quirk in the IDE, or are these
  properties only present/active under certain circumstances?

May be quirk in the IDE.We have official doc that says the property exits.


问:
How to upgrade node js version on google cloud build
So I recently upgraded my app from Angular 7 to Angular 8 and I'm having issues with the node version of the cloud build VM as Angular 8 requires node version 10.9 or greater as shown below:

How can I upgrade the node version of the Google cloud VM so I won't get this error again?

Thanks.

答:
Ok, so after hours of Googling around it turns out Google cloud platform offers a registry of different npm cloud builders for use with Google cloud build.

I could have solved my issue by creating my own docker image but I wanted to avoid this in favour of the default cloud builders docker image. I changed my cloudbuild.yaml file to include the following builder 'gcr.io/cloud-builders/npm:node-10.10.0' instead of 'gcr.io/cloud-builders/npm' this then updated the node version to node 10.10.0 and just like magic Angular 8 can now be built by google cloud build!

Specific node versions from the cloud builders repository can be found here: https://console.cloud.google.com/gcr/images/cloud-builders/GLOBAL/npm


问:
How to make multipages and layout (or) container with React Router?
I'm making a dashboard, using React Router v4. I have pages such as Sign up, Sign in, Add and List products, Add and List customers.

Authentication pages, Sign up and Sign in pages are with their own layouts, no, header or footer or nav manu. The rest share the same layout design, with header, nav menu and footer.

I've tried this:

```<code>// App.tsx

return (
  <Router>
    <Route exact path="/" component={Layout}>
      <Route exact path="/" component={Status} />
      <Route path="/welcome" component={Welcome} />
    </Route>
    <Route path="/signup" component={SignUp} />
    <Route path="/signin" component={SignIn} />
  </Router>
);
</code>```

```<code>// Layout.tsx

return (
  <React.Fragment>
    <Header lastName="Wahaha" />
    <Navbar />
    {children}
    <Footer description="Thanks for visiting!" />
  </React.Fragment>
);
</code>```

, <Navbar />, and  are not appeared though.

Took a reference from here: Using multiple layouts for react-router components but it doesn't work for me.

Please help.

答:
In my projects, I use to create specific routes to handle that. For instance, I have RouteAuthenticated, RouteUnauthenticated, RouteAdmin...

```<code>// RouteAuthenticated

import { Redirect, Route } from 'react-router-dom';

class RouteAuthenticated extends React.Component<Props, State> {
    constructor(props) {
        super(props);
        this.state = {
            isAuthenticated: false,
            loading: true,
        };
    }

    async componentDidMount() {
        const isAuthenticated = CHECK IF IS AUTHENTICATED
        this.setState({
            isAuthenticated,
            loading: false,
        });
    }

    render() {
        const { component: Component, ...rest } = this.props;
        const { isAuthenticated, loading } = this.state;
        const renderRoute = props =>
            isAuthenticated === true ? (
                <Layout>
                    <Component {...props} />
                </Layout>
            ) : (
                <Redirect to="/signup" />
            );
        return loading ? null : <Route {...rest} render={renderRoute} />;
    }
}

export default RouteAuthenticated;
</code>```

This way I take care of wrapping and authentication in a single component.

In App.tsx

```<code>// App.tsx

return (
  <Switch>
    <RouteAuthenticated exact path="/" component={Status} />
    <RouteAuthenticated path="/welcome" component={Welcome} />
    <RouteUnauthenticated path="/signup" component={SignUp} /> // or     <Route path="/signup" component={SignUp} />
    <RouteUnauthenticated path="/signin" component={SignIn} /> // or     <Route path="/signin" component={SignIn} />
  </Switch>
);
</code>```

Body:
I'm making a dashboard, using React Router v4. I have pages such as Sign up, Sign in, Add and List products, Add and List customers.

Authentication pages, Sign up and Sign in pages are with their own layouts, no, header or footer or nav manu. The rest share the same layout design, with header, nav menu and footer.

I've tried this:

// App.tsx

return (
  <Router>
    <Route exact path="/" component={Layout}>
      <Route exact path="/" component={Status} />
      <Route path="/welcome" component={Welcome} />
    </Route>
    <Route path="/signup" component={SignUp} />
    <Route path="/signin" component={SignIn} />
  </Router>
);

// Layout.tsx

return (
  <React.Fragment>

    <Navbar />
    {children}

  </React.Fragment>
);

, <Navbar />, and  are not appeared though.

Took a reference from here: Using multiple layouts for react-router components but it doesn't work for me.

Please help.

Body:
In my projects, I use to create specific routes to handle that. For instance, I have RouteAuthenticated, RouteUnauthenticated, RouteAdmin...

// RouteAuthenticated

import { Redirect, Route } from 'react-router-dom';

class RouteAuthenticated extends React.Component<Props, State> {
    constructor(props) {
        super(props);
        this.state = {
            isAuthenticated: false,
            loading: true,
        };
    }

    async componentDidMount() {
        const isAuthenticated = CHECK IF IS AUTHENTICATED
        this.setState({
            isAuthenticated,
            loading: false,
        });
    }

    render() {
        const { component: Component, ...rest } = this.props;
        const { isAuthenticated, loading } = this.state;
        const renderRoute = props =>
            isAuthenticated === true ? (
                <Layout>
                    <Component {...props} />
                </Layout>
            ) : (
                <Redirect to="/signup" />
            );
        return loading ? null : <Route {...rest} render={renderRoute} />;
    }
}

export default RouteAuthenticated;

This way I take care of wrapping and authentication in a single component.

In App.tsx

// App.tsx

return (
  <Switch>
    <RouteAuthenticated exact path="/" component={Status} />
    <RouteAuthenticated path="/welcome" component={Welcome} />
    <RouteUnauthenticated path="/signup" component={SignUp} /> // or     <Route path="/signup" component={SignUp} />
    <RouteUnauthenticated path="/signin" component={SignIn} /> // or     <Route path="/signin" component={SignIn} />
  </Switch>
);


问:
substracting date times in pandas
i've data frame is this

```<code>In[1]: df1
Out[1]
   Loan Date Negotiation
   2019-03-31
   2019-03-31
   2019-03-31

as Loan Date Negotiation           datetime64[ns]
</code>```

so i wanna make function to subtract 2 days from it. if last the day of the month is sunday, i will subtract 2 days from it.

From dataframe above, 2019-03-31 Is sunday,

i've tried but it's fail, this is

```<code> def subtractingDate(dateTime):
     dateTimestamp = pd.Timestamp(dateTime)
     newDate = dateTimestamp - pd.Timedelta("2 days")
     return newDate

 dfMARET.loc[dfMARET["Loan Date Negotiation"].dt.dayofweek == 6, "New Date"] = subtractingDate(dfMARET["Loan Date Negotiation"])

*note: 6 is for sunday

So the error is

TypeError                                 Traceback (most recent call last)
<ipython-input-9-cc2a3348e6ce> in <module>
     16 # a = subtractingDate(dfMARET["Loan Date Negotiation"])
     17 # a
---> 18 dfMARET.loc[dfMARET["Loan Date Negotiation"].dt.dayofweek == 6, "New Date"] = subtractingDate(dfMARET["Loan Date Negotiation"])
     19 dfMARET
     20

<ipython-input-9-cc2a3348e6ce> in subtractingDate(dateTime)
     10
     11 def subtractingDate(dateTime):
---> 12     dateTimestamp = pd.Timestamp(dateTime)
     13     newDate = dateTimestamp - pd.Timedelta(days = 2)
     14     return newDate

pandas\_libs\tslibs\timestamps.pyx in pandas._libs.tslibs.timestamps.Timestamp.__new__()

pandas\_libs\tslibs\conversion.pyx in pandas._libs.tslibs.conversion.convert_to_tsobject()```

```

<p><strong>so my expectation would be</strong></p>

``` Loan Date Negotiation
 2019-03-29
 2019-03-29
 2019-03-29
```

Ther's solution in pandas?

thank's

答:
You're close!  You just need to change what you pass into Timedelta().

Here's an example:

```<code>import pandas as pd

ts = pd.Timestamp(2017, 1, 1, 12)
days = pd.Timedelta(days=2)
print(days)
print(ts)
print(ts - days)
</code>```

Output:

```<code>2 days 00:00:00
2017-01-01 12:00:00
2016-12-30 12:00:00
</code>```

Title: substracting date times in pandas

Body:
i've data frame is this

In[1]: df1
Out[1]
   Loan Date Negotiation
   2019-03-31
   2019-03-31
   2019-03-31

as Loan Date Negotiation           datetime64[ns]

so i wanna make function to subtract 2 days from it. if last the day of the month is sunday, i will subtract 2 days from it.

From dataframe above, 2019-03-31 Is sunday,

i've tried but it's fail, this is

 def subtractingDate(dateTime):
     dateTimestamp = pd.Timestamp(dateTime)
     newDate = dateTimestamp - pd.Timedelta("2 days")
     return newDate

 dfMARET.loc[dfMARET["Loan Date Negotiation"].dt.dayofweek == 6, "New Date"] = subtractingDate(dfMARET["Loan Date Negotiation"])

*note: 6 is for sunday

So the error is

TypeError                                 Traceback (most recent call last)
<ipython-input-9-cc2a3348e6ce> in <module>
     16 # a = subtractingDate(dfMARET["Loan Date Negotiation"])
     17 # a
---> 18 dfMARET.loc[dfMARET["Loan Date Negotiation"].dt.dayofweek == 6, "New Date"] = subtractingDate(dfMARET["Loan Date Negotiation"])
     19 dfMARET
     20

<ipython-input-9-cc2a3348e6ce> in subtractingDate(dateTime)
     10
     11 def subtractingDate(dateTime):
---> 12     dateTimestamp = pd.Timestamp(dateTime)
     13     newDate = dateTimestamp - pd.Timedelta(days = 2)
     14     return newDate

pandas\_libs\tslibs\timestamps.pyx in pandas._libs.tslibs.timestamps.Timestamp.__new__()

pandas\_libs\tslibs\conversion.pyx in pandas._libs.tslibs.conversion.convert_to_tsobject()```

so my expectation would be

 Loan Date Negotiation
 2019-03-29
 2019-03-29
 2019-03-29

Ther's solution in pandas?

thank's

Body:
You're close!  You just need to change what you pass into Timedelta().

Here's an example:

import pandas as pd

ts = pd.Timestamp(2017, 1, 1, 12)
days = pd.Timedelta(days=2)
print(days)
print(ts)
print(ts - days)

Output:

2 days 00:00:00
2017-01-01 12:00:00
2016-12-30 12:00:00


答:
You can use lodash's _.some() (which works with objects), and lodash/vanilla includes to find if the current property's value has the search string:

const includesValue = (val, obj) => _.some(obj, v => _.includes(v, val))

const obj = {first: "Fred", last: "Flintstone",}
const search = "stone";
const result = includesValue(search, obj)

console.log(result); // true```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script></code>```

And a lodash/fp version:

const includesValue = val => _.some(_.includes(val))

const obj = {first: "Fred", last: "Flintstone",}
const search = "stone";
const result = includesValue(search)(obj)

console.log(result); // true```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script></code>```

To handle case sensitivity and letters with diacritics, you can use _.deburr() (or the this answer), and convert the text to lower case:

const normalize = str => _.toLower(_.deburr(str))

const includesValue = (val, obj) => {
  const search = normalize(val)
  return _.some(obj, v => normalize(v).includes(search))
}

const obj = {first: "Fred", last: "Flintstoné",}
const search = "Stone";
const result = includesValue(search, obj)

console.log(result); // true```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script></code>```

Title: Using Lodash to find a partial string in any property value of an object

Body:
You can use lodash's _.some() (which works with objects), and lodash/vanilla includes to find if the current property's value has the search string:

const includesValue = (val, obj) => _.some(obj, v => _.includes(v, val))

const obj = {first: "Fred", last: "Flintstone",}
const search = "stone";
const result = includesValue(search, obj)

console.log(result); // true

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

And a lodash/fp version:

const includesValue = val => _.some(_.includes(val))

const obj = {first: "Fred", last: "Flintstone",}
const search = "stone";
const result = includesValue(search)(obj)

console.log(result); // true

<script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>

To handle case sensitivity and letters with diacritics, you can use _.deburr() (or the this answer), and convert the text to lower case:

const normalize = str => _.toLower(_.deburr(str))

const includesValue = (val, obj) => {
  const search = normalize(val)
  return _.some(obj, v => normalize(v).includes(search))
}

const obj = {first: "Fred", last: "Flintstoné",}
const search = "Stone";
const result = includesValue(search, obj)

console.log(result); // true

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>


问:
How to write for loop to fetch data to newly created file?
I have scenario where I want to fetch the above 2 lines from where it as matched

I have two files:

file 1

```<code>Ag
Ab
Ah
Av
Ax
</code>```

file 2

```<code>jb:fun_0
jb:fun_jack_0
jb1:Ag

jb:fun_1
jb:fun_jack_1
jb1:Ab

jb:fun_2
jb:fun_jack_3
jb1:Ai

jb:fun_4
jb:fun_jack_4
jb1:Ah

jb:fun_5
jb:fun_jack_5
jb1:Av

jb:fun_5
jb:fun_jack_5
jb1:Al

jb:fun_5
jb:fun_jack_5
jb1:Aj

jb:fun_5
jb:fun_jack_5
jb1:Ax
</code>```

I want to add for loop => like

first it will take the word from file1 => like Ag => try to find Ag in the
file 2 => if match found then above 2 lines from where it as match should be written to a new text file => demo.txt

my code

```<code>for j in file1
do
  sr=`grep -i -B2 '$j' file2`
  echo $sr>>demo.txt
done
</code>```

But the above code is not working => suggest me

expected output:
Ag match found in file2 => above 2 lines of match should be printed

like output:

```<code>=======================
jb:fun_0       # 1st line
jb:fun_jack_0  # 2nd line
jb1:Ag         # => match found
=======================
jb:fun_1       # 1st line
jb:fun_jack_1  # 2nd line
jb1:Ab         # => match found
=======================
</code>```

that how the output will on match above 2 lines should be printed

答:
You can use the following :

```<code>grep -wFB2 -f file2 file1 > demo.txt
</code>```

Detail of the grep options :

-w match only full words : avoid matching Avoid when looking for Av

-B2 output the two previous lines in addition to matching lines

-f file2 read patterns from file2

-F the patterns are linefeed-separated plain text, not regexs

You can try it here !

Body:
I have scenario where I want to fetch the above 2 lines from where it as matched

I have two files:

file 1

Ag
Ab
Ah
Av
Ax

file 2

jb:fun_0
jb:fun_jack_0
jb1:Ag

jb:fun_1
jb:fun_jack_1
jb1:Ab

jb:fun_2
jb:fun_jack_3
jb1:Ai

jb:fun_4
jb:fun_jack_4
jb1:Ah

jb:fun_5
jb:fun_jack_5
jb1:Av

jb:fun_5
jb:fun_jack_5
jb1:Al

jb:fun_5
jb:fun_jack_5
jb1:Aj

jb:fun_5
jb:fun_jack_5
jb1:Ax

I want to add for loop => like

first it will take the word from file1 => like Ag => try to find Ag in the
file 2 => if match found then above 2 lines from where it as match should be written to a new text file => demo.txt

my code

for j in file1
do
  sr=`grep -i -B2 '$j' file2`
  echo $sr>>demo.txt
done

But the above code is not working => suggest me

expected output:
Ag match found in file2 => above 2 lines of match should be printed

like output:

=======================
jb:fun_0       # 1st line
jb:fun_jack_0  # 2nd line
jb1:Ag         # => match found
=======================
jb:fun_1       # 1st line
jb:fun_jack_1  # 2nd line
jb1:Ab         # => match found
=======================

that how the output will on match above 2 lines should be printed

Body:
You can use the following :

grep -wFB2 -f file2 file1 > demo.txt

Detail of the grep options :

-w match only full words : avoid matching Avoid when looking for Av

-B2 output the two previous lines in addition to matching lines

-f file2 read patterns from file2

-F the patterns are linefeed-separated plain text, not regexs

You can try it here !


问:
Is their a way to change the selected index of a picker from a button click on another page?
So i am trying to change the selected index of my picker when a user clicks on button on a different page. The user is able to click on a certain doctor from a list view which then directs them to the add appointment page. From here there is a drop down list auto populated with all the users doctors. The dropdown remains blank until the user picks which doctor they want.

Is it possible to change the selected index of doctor dropdown to match the doctor in the list from the previous page once the button is clicked ?

Any help would be greatly appreciated. Beginner in Xamarin

答:
Jason is right here. you can pass the index to the new page and in OnAppearing set SelectedIndex = passedIndex in your view model. This is if you have SelectedIndex bound to a property in your view model.

if you're using SelectedItem you'll need to  find the doctor object and use that to set SelectedItem in your view model. ex. SelectedItem = DoctorList.IndexOf(passedIndex) or if passing the doctor object SelectedItem = DoctorList.First(doc => doc.Id == passedDoc.Id).


问:
R Markdown not knitting due to rbind error
I'm a new RMarkdown user trying to render a .Rmd file to Word and I haven't been able to get it to spit out anything at all.  Every time that I try to knit the file, I get the following error:

```<code>Error in rbind(info, getNamespaceInfo(env, "S3methods")) :
  number of columns of matrices must match (see arg 2)
Calls: :: ... tryCatch -> tryCatchList -> tryCatchOne -> <Anonymous>
Execution halted
</code>```

I started by reinstalling the "knitr" and "evaluate" packages (the latter due to an answer to a separate question) and then pared down the code to just the bare bones:

```<code>---
title: "Untitled"
author: "Anonymous"
output: word_document
---
Test
</code>```

Not even this small amount of code works, with each attempt to knit things together resulting in the same error as above.

What am I missing?

答:
From this thread in the R-devel mailing list, it seems one or some of your R packages are broken. Two things you can try:

Upgrade R and R packages. Run update.packages(ask = FALSE, checkBuilt = TRUE) after you have installed a newer version of R.

If that doesn't fix the problem, reinstall all packages: install.packages(.packages(TRUE)) (this is not the ideal way to reinstall packages when you have multiple library paths .libPaths()).

Body:
I'm a new RMarkdown user trying to render a .Rmd file to Word and I haven't been able to get it to spit out anything at all.  Every time that I try to knit the file, I get the following error:

Error in rbind(info, getNamespaceInfo(env, "S3methods")) :
  number of columns of matrices must match (see arg 2)
Calls: :: ... tryCatch -> tryCatchList -> tryCatchOne -> <Anonymous>
Execution halted

I started by reinstalling the "knitr" and "evaluate" packages (the latter due to an answer to a separate question) and then pared down the code to just the bare bones:

---
title: "Untitled"
author: "Anonymous"
output: word_document
---
Test

Not even this small amount of code works, with each attempt to knit things together resulting in the same error as above.

What am I missing?