问:
How to pass assumptions to interpretation of locale
I would like to use some properties of my structure in the proof required by a locale interpretation

As an example, suppose I defined the predicate P and proved some lemmas (add is a closed binary operation, add is associative and there exists zero the neutral element) about the add operation on elements that satisfy the predicate P

I would like to interpret then the set of my elements as a structure that
satisfy some locale, e.g. monoid

```<code>interpretation "{s . P s}" :: monoid "(add)" "(zero)"
unfolding
  monoid_def
using
  add_is_associative
  zero_is_neutral
</code>```

but then in the goal of my proof I am not able to get that all the elements
are actually satisfying the predicate P and I am left with a generic goal
such as add zero a = a which I already proved for elements in my set.

How to enforce in my goal that all the elements satisfy the predicate P?

答:
I will make an attempt to provide comments on your question. Please feel free to ask further questions in the comments if you will find that my comments are not sufficient to answer your question.

Firstly, I would like to mention that there exists a good tutorial on locales and locale interpretation in the standard documentation of Isabelle. The name of the document is "Tutorial to Locales and Locale Interpretation" (by Clemens Ballarin). The document also contains several useful references.

After studying the tutorial and the references, it may also be useful to look at section 5.7 in the document "The Isabelle/Isar Reference Manual".

I would like to use some properties of my structure in the proof
  required by a locale interpretation

The description of the locale interpretation in the reference manual states that

Locales may be instantiated, and the resulting instantiated
  declarations added to the current context. This requires proof (of the
  instantiated specification) and is called locale interpretation.

When you invoke the command interpretation with a set of appropriately stated arguments, the goals that are discharged by the command depend solely on the arguments. The proof that you provide to prove the discharged goals will have no impact on the 'resulting instantiated declarations'. Thus, technically, it does not matter whether or not you use the properties of your functions that you mentioned explicitly to prove the interpretation.

I would like to interpret then the set of my elements as a structure
  that satisfy some locale, e.g. monoid:
  interpretation "{s . P s}" :: monoid "(add)" "(zero)"

If you look at the specification of the command interpretation in the reference manual (section 5.7.3), you will realise that as its input argument the command takes a 'locale expression'. The 'locale expression' is described in section 5.7.1 in the reference manual. Here, I present a significantly simplified (incomplete) description of the locale expression:

qualifier : name pos_insts

The field 'qualifier' is optional and the field 'name' is reserved for the name of the locale that you are trying to interpret. Therefore, the expression "{s . P s}" :: monoid "(add)" "(zero)" that you provided in your question is not a valid locale expression. I can only guess that you meant to use a single colon instead of the double colon ::, i.e. "{s . P s}" : monoid "(add)" "(zero)" and I will proceed with the answer based on this assumption.

In the example that you provided, the 'qualifier' is "{s . P s}", the 'name' is monoid and the 'pos_insts' are, effectively, the terms specified after the name.

Returning to the documentation you will also find the description of the field 'qualifier':

Instances have an optional qualifier which applies to names in
  declarations

...

Qualifiers only affect name spaces; they play no role in
  determining whether one locale instance subsumes another.

Thus, the qualifier "{s . P s}" that you specified can only have an effect on the names of the declarations. It will have no effect on the goals discharged by the command and its output.

interpretation "{s . P s}" : monoid "(add)" "(zero)"

Returning to your example, if you are referring to the locale monoid from the theory HOL-Groups, then, if you study its specification and also the specification of the locale semigroup, you will be able to infer that the locale monoid has two parameters that are associated with it: f and z. There are no other parameters and the 'carrier set' of the monoid associated with the locale consists of all terms of a given type.

```<code>locale monoid = semigroup +
  fixes z :: 'a ("❙1")
  assumes left_neutral [simp]: "❙1 ❙* a = a"
  assumes right_neutral [simp]: "a ❙* ❙1 = a"
</code>```

In conclusion, the locale monoid from the theory HOL-Groups is not suitable for representation of a monoid on an explicit carrier set that is a proper subset of the terms of a given type.

For your application, you will need to use a locale that represents a monoid on an explicit carrier set, for example, the locale monoid from the theory HOL-Algebra.Group. You can see examples of its interpretation in the theory HOL-Algebra.IntRing.

UPDATE

Following the request of the author of the question given in the comments, I provide an example of an interpretation of the locale monoid from the theory HOL-Algebra.Group:

```<code>theory SO_Question
  imports "HOL-Algebra.Group"

begin

abbreviation even_monoid :: "int monoid" ("⇩2") where
  "even_monoid ≡ ⦇carrier = {x. x mod 2 = 0}, mult = (+), one = 0::int⦈"

interpretation even_monoid: monoid ⇩2
  by unfold_locales auto+

end
</code>```

Body:
I would like to use some properties of my structure in the proof required by a locale interpretation

As an example, suppose I defined the predicate P and proved some lemmas (add is a closed binary operation, add is associative and there exists zero the neutral element) about the add operation on elements that satisfy the predicate P

I would like to interpret then the set of my elements as a structure that
satisfy some locale, e.g. monoid

interpretation "{s . P s}" :: monoid "(add)" "(zero)"
unfolding
  monoid_def
using
  add_is_associative
  zero_is_neutral

but then in the goal of my proof I am not able to get that all the elements
are actually satisfying the predicate P and I am left with a generic goal
such as add zero a = a which I already proved for elements in my set.

How to enforce in my goal that all the elements satisfy the predicate P?

Body:
I will make an attempt to provide comments on your question. Please feel free to ask further questions in the comments if you will find that my comments are not sufficient to answer your question.

Firstly, I would like to mention that there exists a good tutorial on locales and locale interpretation in the standard documentation of Isabelle. The name of the document is "Tutorial to Locales and Locale Interpretation" (by Clemens Ballarin). The document also contains several useful references.

After studying the tutorial and the references, it may also be useful to look at section 5.7 in the document "The Isabelle/Isar Reference Manual".

I would like to use some properties of my structure in the proof
  required by a locale interpretation

The description of the locale interpretation in the reference manual states that

Locales may be instantiated, and the resulting instantiated
  declarations added to the current context. This requires proof (of the
  instantiated specification) and is called locale interpretation.

When you invoke the command interpretation with a set of appropriately stated arguments, the goals that are discharged by the command depend solely on the arguments. The proof that you provide to prove the discharged goals will have no impact on the 'resulting instantiated declarations'. Thus, technically, it does not matter whether or not you use the properties of your functions that you mentioned explicitly to prove the interpretation.

I would like to interpret then the set of my elements as a structure
  that satisfy some locale, e.g. monoid:
  interpretation "{s . P s}" :: monoid "(add)" "(zero)"

If you look at the specification of the command interpretation in the reference manual (section 5.7.3), you will realise that as its input argument the command takes a 'locale expression'. The 'locale expression' is described in section 5.7.1 in the reference manual. Here, I present a significantly simplified (incomplete) description of the locale expression:

qualifier : name pos_insts

The field 'qualifier' is optional and the field 'name' is reserved for the name of the locale that you are trying to interpret. Therefore, the expression "{s . P s}" :: monoid "(add)" "(zero)" that you provided in your question is not a valid locale expression. I can only guess that you meant to use a single colon instead of the double colon ::, i.e. "{s . P s}" : monoid "(add)" "(zero)" and I will proceed with the answer based on this assumption.

In the example that you provided, the 'qualifier' is "{s . P s}", the 'name' is monoid and the 'pos_insts' are, effectively, the terms specified after the name.

Returning to the documentation you will also find the description of the field 'qualifier':

Instances have an optional qualifier which applies to names in
  declarations

...

Qualifiers only affect name spaces; they play no role in
  determining whether one locale instance subsumes another.

Thus, the qualifier "{s . P s}" that you specified can only have an effect on the names of the declarations. It will have no effect on the goals discharged by the command and its output.

interpretation "{s . P s}" : monoid "(add)" "(zero)"

Returning to your example, if you are referring to the locale monoid from the theory HOL-Groups, then, if you study its specification and also the specification of the locale semigroup, you will be able to infer that the locale monoid has two parameters that are associated with it: f and z. There are no other parameters and the 'carrier set' of the monoid associated with the locale consists of all terms of a given type.

locale monoid = semigroup +
  fixes z :: 'a ("❙1")
  assumes left_neutral [simp]: "❙1 ❙* a = a"
  assumes right_neutral [simp]: "a ❙* ❙1 = a"

In conclusion, the locale monoid from the theory HOL-Groups is not suitable for representation of a monoid on an explicit carrier set that is a proper subset of the terms of a given type.

For your application, you will need to use a locale that represents a monoid on an explicit carrier set, for example, the locale monoid from the theory HOL-Algebra.Group. You can see examples of its interpretation in the theory HOL-Algebra.IntRing.

UPDATE

Following the request of the author of the question given in the comments, I provide an example of an interpretation of the locale monoid from the theory HOL-Algebra.Group:

theory SO_Question
  imports "HOL-Algebra.Group"

begin

abbreviation even_monoid :: "int monoid" ("⇩2") where
  "even_monoid ≡ ⦇carrier = {x. x mod 2 = 0}, mult = (+), one = 0::int⦈"

interpretation even_monoid: monoid ⇩2
  by unfold_locales auto+

end


来源: stackexchange

问:
Set.visible isn't actually doing anything for me, or thread.sleep is screwing me over
My pulseRed (pulse a red jButton) method should make the button visible, wait one second, then make it invisible again. I have the button started as invisible by the way. However when i run it, the button is never set to be visible. I have print statements that say that it should be setting them visible, but it doesn't. I don't know if it is a problem with the timer or the set.visible part.

I have tried different timers, but they are all kinda complicated and I'm sorta new to java. I did try instead of making the button visible then invisible, make the button bigger and smaller to simulate a pulse. But that also didn't work, which makes me think its a timer problem.

Heres the code:

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class redButtonPulseQuestionCode {
    private static JButton redButton = redButton();
    private static JButton startButton = new JButton("Start");

    redButtonPulseQuestionCode() {
        JFrame colorFrame = new JFrame("Simon Says Game");
        JPanel colorPanel = new JPanel();

        colorPanel.setBounds(0, 0, 500, 500);
        colorPanel.setBackground(Color.DARK_GRAY);
        colorFrame.setLayout(null);
        colorPanel.setLayout(null);

        startButton.setBackground(Color.white);

        colorPanel.add(redButton);
        colorPanel.add(startButton);

        redButton.setBounds(50, 175, 100, 100);
        redButton.setVisible(false);

        startButton.setBounds(335, 400, 100, 50);

        colorFrame.add(colorPanel);
        colorFrame.setSize(500,500);
        colorFrame.setLocationRelativeTo(null); //sets the game to the center of the screen
        colorFrame.setLayout(null);
        colorFrame.setVisible(true);
        colorFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public static void main(String [] args) {
        new redButtonPulseQuestionCode();
        startButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                    // does stuff when the start button is pressed
                        //setEveryButtonInvisible();
                        startGame();
                }
            });
    }

    public static JButton redButton() {
        JButton redButton = new JButton();
        redButton.setBackground(Color.red);
        return redButton;
    }

    public static void timer1()
    {
        try
        {
            Thread.sleep(1000);
        } catch(InterruptedException ie)
        {

        }
    }

    public static void pulseRed() {
        redButton.setVisible(true);
        System.out.println("set red visible");
        timer1();
        redButton.setVisible(false);
        System.out.println("set red invisible");
    }

    public static void startGame() {
        boolean userAnswer = true;
        int round = 0;
        System.out.println("Start game");
        pulseRed();

}
}
```

It should, theoretically, when you press the start button, make the red button visible, and then turn it off after a 1 second delay. But in the case of this code, it doesn't appear, but the print statements do work.

答:
You shouldn't just call Thread.sleep on the UI thread of a GUI app like that.

What is happening is, you set the button to be visible, but before the screen has a chance to update the button's visibility, you tell the thread sleep. This stops the screen from updating the button. After the screen "wakes up", you set the button to be invisible again. This is why you never see the button appear.

What you should do is to use a Timer. You can use the java.swing.Timer, like this:

```<code>redButton.setVisible(true);
Timer t = new Timer(1000, e -> {
    redButton.setVisible(false);
});
t.setRepeats(false);
t.start();
</code>```

ContentLicense: CC BY-SA 4.0

Body:
My pulseRed (pulse a red jButton) method should make the button visible, wait one second, then make it invisible again. I have the button started as invisible by the way. However when i run it, the button is never set to be visible. I have print statements that say that it should be setting them visible, but it doesn't. I don't know if it is a problem with the timer or the set.visible part.

I have tried different timers, but they are all kinda complicated and I'm sorta new to java. I did try instead of making the button visible then invisible, make the button bigger and smaller to simulate a pulse. But that also didn't work, which makes me think its a timer problem.

Heres the code:

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class redButtonPulseQuestionCode {
    private static JButton redButton = redButton();
    private static JButton startButton = new JButton("Start");

    redButtonPulseQuestionCode() {
        JFrame colorFrame = new JFrame("Simon Says Game");
        JPanel colorPanel = new JPanel();

        colorPanel.setBounds(0, 0, 500, 500);
        colorPanel.setBackground(Color.DARK_GRAY);
        colorFrame.setLayout(null);
        colorPanel.setLayout(null);

        startButton.setBackground(Color.white);

        colorPanel.add(redButton);
        colorPanel.add(startButton);

        redButton.setBounds(50, 175, 100, 100);
        redButton.setVisible(false);

        startButton.setBounds(335, 400, 100, 50);

        colorFrame.add(colorPanel);
        colorFrame.setSize(500,500);
        colorFrame.setLocationRelativeTo(null); //sets the game to the center of the screen
        colorFrame.setLayout(null);
        colorFrame.setVisible(true);
        colorFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public static void main(String [] args) {
        new redButtonPulseQuestionCode();
        startButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                    // does stuff when the start button is pressed
                        //setEveryButtonInvisible();
                        startGame();
                }
            });
    }

    public static JButton redButton() {
        JButton redButton = new JButton();
        redButton.setBackground(Color.red);
        return redButton;
    }

    public static void timer1()
    {
        try
        {
            Thread.sleep(1000);
        } catch(InterruptedException ie)
        {

        }
    }

    public static void pulseRed() {
        redButton.setVisible(true);
        System.out.println("set red visible");
        timer1();
        redButton.setVisible(false);
        System.out.println("set red invisible");
    }

    public static void startGame() {
        boolean userAnswer = true;
        int round = 0;
        System.out.println("Start game");
        pulseRed();

}
}

It should, theoretically, when you press the start button, make the red button visible, and then turn it off after a 1 second delay. But in the case of this code, it doesn't appear, but the print statements do work.

Body:
You shouldn't just call Thread.sleep on the UI thread of a GUI app like that.

What is happening is, you set the button to be visible, but before the screen has a chance to update the button's visibility, you tell the thread sleep. This stops the screen from updating the button. After the screen "wakes up", you set the button to be invisible again. This is why you never see the button appear.

What you should do is to use a Timer. You can use the java.swing.Timer, like this:

redButton.setVisible(true);
Timer t = new Timer(1000, e -> {
    redButton.setVisible(false);
});
t.setRepeats(false);
t.start();


问:
My code works on VB syntax but not on C# syntax
In my vb.net I have this code:

```<code>Private WithEvents RF As SiritController2._0.RFIDController

Public Sub StartReaders()
    RF = New SiritController2._0.RFIDController(HP.RfIdAddress, HP.RfIdUserName, HP.RfIdPassword, HP.RfIdAntena)
EndSub
</code>```

In my c# I have this code:

```<code>private RFIDController reader;

private void Start()
{
    reader = new RFIDController(HP.RfIdAddress, "HP.RfIdUserName", "HP.RfIdPassword", HP.RfIdAntena);
    reader.DetectRFID += Reader_DetectRFID;
}
</code>```

These 2 codes are calling the same class on the same constructor

```<code>public RFIDController(string HostIP, string userName, string userPass, string AntennaNoPort = "1")
{
  RFIDController.__ENCAddToList((object) this);
  this.SvcTimerInterval = 45000;
  this.ReaderTimeOut = 1000;
  this.RaiseEventDelay = 0;
  this._lastReadRFTagNumber = string.Empty;
  this._LRRFT = new RFIDController.LastReadRFTagNumber();
  try
  {
    if (string.IsNullOrEmpty(userName) | string.IsNullOrEmpty(userPass))
      throw new Exception("Reader username or password cannot be empty.");
    this.IPAddress = HostIP;
    this.ReaderUser = userName;
    this.ReaderPW = userPass;
    this.AntennaNo = AntennaNoPort;
    this.Connect();
  }
  catch (Exception ex)
  {
    ProjectData.SetProjectError(ex);
    throw new Exception("Error occured while instantiating controller : " + ex.InnerException.ToString());
  }
}
</code>```

Why is it that I get an error of

"Object reference not set to an instance"

in my C# code but not in my VB code? Upon inspection, I can see my parameters get filled.

答:
This

```<code>reader = new RFIDController(HP.RfIdAddress, "HP.RfIdUserName", "HP.RfIdPassword", HP.RfIdAntena);
</code>```

Should be:

```<code>reader = new RFIDController(HP.RfIdAddress, HR.RfIdUserName, HP.RfIdPassword, HP.RfIdAntena);
</code>```

Also not every Exception has an InnerException.  So that can cause the NullReferenceException, hiding the real error when the catch block calls:

```<code>ex.InnerException.ToString()
</code>```

Body:
In my vb.net I have this code:

Private WithEvents RF As SiritController2._0.RFIDController

Public Sub StartReaders()
    RF = New SiritController2._0.RFIDController(HP.RfIdAddress, HP.RfIdUserName, HP.RfIdPassword, HP.RfIdAntena)
EndSub

In my c# I have this code:

private RFIDController reader;

private void Start()
{
    reader = new RFIDController(HP.RfIdAddress, "HP.RfIdUserName", "HP.RfIdPassword", HP.RfIdAntena);
    reader.DetectRFID += Reader_DetectRFID;
}

These 2 codes are calling the same class on the same constructor

public RFIDController(string HostIP, string userName, string userPass, string AntennaNoPort = "1")
{
  RFIDController.__ENCAddToList((object) this);
  this.SvcTimerInterval = 45000;
  this.ReaderTimeOut = 1000;
  this.RaiseEventDelay = 0;
  this._lastReadRFTagNumber = string.Empty;
  this._LRRFT = new RFIDController.LastReadRFTagNumber();
  try
  {
    if (string.IsNullOrEmpty(userName) | string.IsNullOrEmpty(userPass))
      throw new Exception("Reader username or password cannot be empty.");
    this.IPAddress = HostIP;
    this.ReaderUser = userName;
    this.ReaderPW = userPass;
    this.AntennaNo = AntennaNoPort;
    this.Connect();
  }
  catch (Exception ex)
  {
    ProjectData.SetProjectError(ex);
    throw new Exception("Error occured while instantiating controller : " + ex.InnerException.ToString());
  }
}

Why is it that I get an error of

"Object reference not set to an instance"

in my C# code but not in my VB code? Upon inspection, I can see my parameters get filled.

Body:
This

reader = new RFIDController(HP.RfIdAddress, "HP.RfIdUserName", "HP.RfIdPassword", HP.RfIdAntena);

Should be:

reader = new RFIDController(HP.RfIdAddress, HR.RfIdUserName, HP.RfIdPassword, HP.RfIdAntena);

Also not every Exception has an InnerException.  So that can cause the NullReferenceException, hiding the real error when the catch block calls:

ex.InnerException.ToString()


问:
I want Shiny UI with multiple inputs in a row
I want shiny sliderInput to be biuld like attached image

side by side values i want like min and max. the input should be manual and not by slider or dropdown

I tried selectInput but its taking one value in a row I want two values in one row

答:
You could use fluidRow() and column(). You start by using a fluidRow() and add columns() within that functions,...

Reproducible example:

```<code>library(shiny)
ui <- fluidPage(
  fluidRow(
    column(width = 3,
           selectInput("min", "Min Price", 1:4)
    ),
    column(width = 3,
           selectInput("max", "Max Price", 1:4)
    )
  ),
  fluidRow(
    column(width = 3,
           selectInput("min2", "Property type", letters[1:4])
    ),
    column(width = 3,
           selectInput("max2", "Bedrooms", 1:4)
    )
  )
)

shinyApp(ui, server = function(input, output){ })
</code>```

Body:
You could use fluidRow() and column(). You start by using a fluidRow() and add columns() within that functions,...

Reproducible example:

library(shiny)
ui <- fluidPage(
  fluidRow(
    column(width = 3,
           selectInput("min", "Min Price", 1:4)
    ),
    column(width = 3,
           selectInput("max", "Max Price", 1:4)
    )
  ),
  fluidRow(
    column(width = 3,
           selectInput("min2", "Property type", letters[1:4])
    ),
    column(width = 3,
           selectInput("max2", "Bedrooms", 1:4)
    )
  )
)

shinyApp(ui, server = function(input, output){ })


问:
click event on svg refuses to play
I found this code at codepen and I tested on jsfiddle, on codepen but...when I add it to a localhost test page the click event doesn't do anything!

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="16px" height="16px" viewBox="0 0 16 16" version="1.1">

     <path fill="#D8D8D8" d="M0,0 L6,0 L6,16 L0,16 L0,0 Z" id="bar1">
      <animate xlink:href="#bar1"
               attributeName="d"
               from="M0,0 L6,0 L6,16 L0,16 L0,0 Z"
                to="M0,0 L6,3.20001221 L6,12.7999878 L0,16 L0,0 Z"
               dur="0.3s"
                fill="freeze"
                begin="startAnimation.begin" />
      <animate xlink:href="#bar1"
               attributeName="d"
                from="M0,0 L6,3.20001221 L6,12.7999878 L0,16 L0,0 Z"
               to="M0,0 L6,0 L6,16 L0,16 L0,0 Z"
               dur="0.3s"
                fill="freeze"
                begin="reverseAnimation.begin" />
    </path>

     <path fill="#D8D8D8" d="M10,0 L16,0 L16,16 L10,16 Z" id="bar2">
      <animate attributeName="d"
                from="M10,0 L16,0 L16,16 L10,16 Z"
                to="M5.9944458,3.20001221 L15,8 L15,8 L5.9944458,12.7999878 Z"
               dur="0.3s"
               fill="freeze"
               begin="startAnimation.begin" />
      <animate attributeName="d"
                from="M5.9944458,3.20001221 L15,8 L15,8 L5.9944458,12.7999878 Z"
                to="M10,0 L16,0 L16,16 L10,16 Z"
               dur="0.3s"
               fill="freeze"
               begin="reverseAnimation.begin" />
    </path>

    <circle cx="16" cy="16" r="16" fill-opacity="0">
      <animate dur="0.01s" id="startAnimation" attributeName="r" values="16; 0" fill="freeze" begin="click" />
      <animate dur="0.01s" attributeName="r" values="0; 16" fill="freeze" begin="reverseAnimation.end" />
    </circle>
    <circle cx="16" cy="16" r="0" fill-opacity="0">
      <animate dur="0.001s" id="reverseAnimation" attributeName="r" values="16; 0" fill="freeze" begin="click" />
      <animate dur="0.001s" attributeName="r" values="0; 16" begin="startAnimation.end"  fill="freeze"  />
    </circle>
  </svg>```
</div>
</div>
</p>

<p>Does anybody had experienced sth similar?
I can't find what I do wrong here... </p>

<p>PS: I also added this style:</p>

```/*
 * Play
 * ----
 */
.play {
   position: absolute;
   z-index: 1000;
   top: 35%;
   left: 35%;
   cursor: pointer;
   margin: 0;
   padding: 0.4em;
   width: 30%;
   height: 30%;
}
```

<p>and modified the 1st line like</p>

```<svg class="play" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="16px" height="16px" viewBox="0 0 16 16" version="1.1">
```

still with no result!

答:
On codepen, if you change the view to look at debug mode it will open a new tab with a full screen view of the page.

View the source and you will see that the page contains the normal HTML head and body tags.

Sample

```<code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test - YouTube Play Pause Button</title>
<style>
      body {
  background: #111;
  text-align: center;
}

svg {
  margin-top: 45vh;
  width: 40px;
  height: 40px;
  cursor: pointer;
}

    </style>
</head>
<body translate="no">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="16px" height="16px" viewBox="0 0 16 16" version="1.1">

    <!-- bar 1 -->
        <path fill="#D8D8D8" d="M0,0 L6,0 L6,16 L0,16 L0,0 Z" id="bar1">
      <animate xlink:href="#bar1"
               attributeName="d"
               from="M0,0 L6,0 L6,16 L0,16 L0,0 Z"
                to="M0,0 L6,3.20001221 L6,12.7999878 L0,16 L0,0 Z"
               dur="0.3s"
                   fill="freeze"
                   begin="startAnimation.begin" />
      <animate xlink:href="#bar1"
               attributeName="d"
                from="M0,0 L6,3.20001221 L6,12.7999878 L0,16 L0,0 Z"
               to="M0,0 L6,0 L6,16 L0,16 L0,0 Z"
               dur="0.3s"
                   fill="freeze"
                   begin="reverseAnimation.begin" />
    </path>

    <!-- horizontal line -->
        <path fill="#D8D8D8" d="M10,0 L16,0 L16,16 L10,16 Z" id="bar2">
      <animate attributeName="d"
                   from="M10,0 L16,0 L16,16 L10,16 Z"
                   to="M5.9944458,3.20001221 L15,8 L15,8 L5.9944458,12.7999878 Z"
               dur="0.3s"
               fill="freeze"
               begin="startAnimation.begin" />
      <animate attributeName="d"
                   from="M5.9944458,3.20001221 L15,8 L15,8 L5.9944458,12.7999878 Z"
                   to="M10,0 L16,0 L16,16 L10,16 Z"
               dur="0.3s"
               fill="freeze"
               begin="reverseAnimation.begin" />
    </path>

    <!--  controls -->
    <!-- these are on top of the visible icon. Their radius changes depending on which is active
    Opacity is set to 0 so you can't see them-->
    <circle cx="16" cy="16" r="16" fill-opacity="0">
      <animate dur="0.01s" id="startAnimation" attributeName="r" values="16; 0" fill="freeze" begin="click" />
      <animate dur="0.01s" attributeName="r" values="0; 16" fill="freeze" begin="reverseAnimation.end" />
    </circle>
    <circle cx="16" cy="16" r="0" fill-opacity="0">
      <animate dur="0.001s" id="reverseAnimation" attributeName="r" values="16; 0" fill="freeze" begin="click" />
      <animate dur="0.001s" attributeName="r" values="0; 16" begin="startAnimation.end"  fill="freeze"  />
    </circle>
  </svg>
  </body>
  </html>
</code>```

Title: click event on svg refuses to play

Body:
I found this code at codepen and I tested on jsfiddle, on codepen but...when I add it to a localhost test page the click event doesn't do anything!

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="16px" height="16px" viewBox="0 0 16 16" version="1.1">

     <path fill="#D8D8D8" d="M0,0 L6,0 L6,16 L0,16 L0,0 Z" id="bar1">
      <animate xlink:href="#bar1"
               attributeName="d"
               from="M0,0 L6,0 L6,16 L0,16 L0,0 Z"
                to="M0,0 L6,3.20001221 L6,12.7999878 L0,16 L0,0 Z"
               dur="0.3s"
                fill="freeze"
                begin="startAnimation.begin" />
      <animate xlink:href="#bar1"
               attributeName="d"
                from="M0,0 L6,3.20001221 L6,12.7999878 L0,16 L0,0 Z"
               to="M0,0 L6,0 L6,16 L0,16 L0,0 Z"
               dur="0.3s"
                fill="freeze"
                begin="reverseAnimation.begin" />
    </path>

     <path fill="#D8D8D8" d="M10,0 L16,0 L16,16 L10,16 Z" id="bar2">
      <animate attributeName="d"
                from="M10,0 L16,0 L16,16 L10,16 Z"
                to="M5.9944458,3.20001221 L15,8 L15,8 L5.9944458,12.7999878 Z"
               dur="0.3s"
               fill="freeze"
               begin="startAnimation.begin" />
      <animate attributeName="d"
                from="M5.9944458,3.20001221 L15,8 L15,8 L5.9944458,12.7999878 Z"
                to="M10,0 L16,0 L16,16 L10,16 Z"
               dur="0.3s"
               fill="freeze"
               begin="reverseAnimation.begin" />
    </path>

    <circle cx="16" cy="16" r="16" fill-opacity="0">
      <animate dur="0.01s" id="startAnimation" attributeName="r" values="16; 0" fill="freeze" begin="click" />
      <animate dur="0.01s" attributeName="r" values="0; 16" fill="freeze" begin="reverseAnimation.end" />
    </circle>
    <circle cx="16" cy="16" r="0" fill-opacity="0">
      <animate dur="0.001s" id="reverseAnimation" attributeName="r" values="16; 0" fill="freeze" begin="click" />
      <animate dur="0.001s" attributeName="r" values="0; 16" begin="startAnimation.end"  fill="freeze"  />
    </circle>
  </svg>

Does anybody had experienced sth similar?
I can't find what I do wrong here...

PS: I also added this style:

/*
 * Play
 * ----
 */
.play {
   position: absolute;
   z-index: 1000;
   top: 35%;
   left: 35%;
   cursor: pointer;
   margin: 0;
   padding: 0.4em;
   width: 30%;
   height: 30%;
}

and modified the 1st line like

<svg class="play" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="16px" height="16px" viewBox="0 0 16 16" version="1.1">

still with no result!

Body:
On codepen, if you change the view to look at debug mode it will open a new tab with a full screen view of the page.

View the source and you will see that the page contains the normal HTML head and body tags.

Sample

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test - YouTube Play Pause Button</title>
<style>
      body {
  background: #111;
  text-align: center;
}

svg {
  margin-top: 45vh;
  width: 40px;
  height: 40px;
  cursor: pointer;
}

    </style>
</head>
<body translate="no">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="16px" height="16px" viewBox="0 0 16 16" version="1.1">

    <!-- bar 1 -->
        <path fill="#D8D8D8" d="M0,0 L6,0 L6,16 L0,16 L0,0 Z" id="bar1">
      <animate xlink:href="#bar1"
               attributeName="d"
               from="M0,0 L6,0 L6,16 L0,16 L0,0 Z"
                to="M0,0 L6,3.20001221 L6,12.7999878 L0,16 L0,0 Z"
               dur="0.3s"
                   fill="freeze"
                   begin="startAnimation.begin" />
      <animate xlink:href="#bar1"
               attributeName="d"
                from="M0,0 L6,3.20001221 L6,12.7999878 L0,16 L0,0 Z"
               to="M0,0 L6,0 L6,16 L0,16 L0,0 Z"
               dur="0.3s"
                   fill="freeze"
                   begin="reverseAnimation.begin" />
    </path>

    <!-- horizontal line -->
        <path fill="#D8D8D8" d="M10,0 L16,0 L16,16 L10,16 Z" id="bar2">
      <animate attributeName="d"
                   from="M10,0 L16,0 L16,16 L10,16 Z"
                   to="M5.9944458,3.20001221 L15,8 L15,8 L5.9944458,12.7999878 Z"
               dur="0.3s"
               fill="freeze"
               begin="startAnimation.begin" />
      <animate attributeName="d"
                   from="M5.9944458,3.20001221 L15,8 L15,8 L5.9944458,12.7999878 Z"
                   to="M10,0 L16,0 L16,16 L10,16 Z"
               dur="0.3s"
               fill="freeze"
               begin="reverseAnimation.begin" />
    </path>

    <!--  controls -->
    <!-- these are on top of the visible icon. Their radius changes depending on which is active
    Opacity is set to 0 so you can't see them-->
    <circle cx="16" cy="16" r="16" fill-opacity="0">
      <animate dur="0.01s" id="startAnimation" attributeName="r" values="16; 0" fill="freeze" begin="click" />
      <animate dur="0.01s" attributeName="r" values="0; 16" fill="freeze" begin="reverseAnimation.end" />
    </circle>
    <circle cx="16" cy="16" r="0" fill-opacity="0">
      <animate dur="0.001s" id="reverseAnimation" attributeName="r" values="16; 0" fill="freeze" begin="click" />
      <animate dur="0.001s" attributeName="r" values="0; 16" begin="startAnimation.end"  fill="freeze"  />
    </circle>
  </svg>
  </body>
  </html>


问:
Cannot access class.contextType within a child component
I want to make a simple React Web Application using Context API. I want to initialize context object in parent component, and want to use it in child component using "class.contextType".

I have read the link.

And I tried to code like below:

DrawArea.js // parent component which holds context provider and a child component

```<code>import React, {Component} from "react";
import DrawReflect from "./DrawReflect";
import "./DrawArea.css";

export const DrawToolContext = React.createContext();

class DrawArea extends Component{

    constructor(props){
        super(props);

        this.state = {
            drawTool: "line"
        };

    }

    render(){
        return (
            <div className="DrawArea">
                <DrawToolContext.Provider value={this.state}>
                    <div className="box reflect">
                        <DrawReflect />
                    </div>
                </DrawToolContext.Provider>
            </div>
        );
    }
}

export default DrawArea;
</code>```

DrawReflect.js // child component which adopts context from DrawArea and use it

```<code>import React, {Component} from "react";
import {DrawToolContext} from "./DrawArea";
import "./DrawReflect.css";

class DrawReflect extends Component{

    render(){
        return (
            <div className="DrawReflect">
                <p>test</p>
            </div>
        );
    }

}

DrawReflect.contextType = DrawToolContext;

export default DrawReflect;
</code>```

But it returns errors saying -
ReferenceError: Cannot access 'DrawToolContext' before initialization.

This is the full error stack:

```<code>Module.DrawToolContext
http://localhost:3000/static/js/main.chunk.js:473:107
Module../src/pages/draw/fragments/DrawReflect.js
D:/CommuMind/front-react/src/pages/draw/fragments/DrawReflect.js:17
  14 |
  15 | }
  16 |
> 17 | DrawReflect.contextType = DrawToolContext;
  18 |
  19 | export default DrawReflect;
View compiled
__webpack_require__
D:/CommuMind/front-react/webpack/bootstrap:781
  778 | };
  779 |
  780 | // Execute the module function
> 781 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
      | ^  782 |
  783 | // Flag the module as loaded
  784 | module.l = true;
View compiled
fn
D:/CommuMind/front-react/webpack/bootstrap:149
  146 |         );
  147 |         hotCurrentParents = [];
  148 |     }
> 149 |     return __webpack_require__(request);
      | ^  150 | };
  151 | var ObjectFactory = function ObjectFactory(name) {
  152 |     return {
View compiled
Module../src/pages/draw/fragments/DrawArea.js
http://localhost:3000/static/js/main.chunk.js:476:70
__webpack_require__
D:/CommuMind/front-react/webpack/bootstrap:781
  778 | };
  779 |
  780 | // Execute the module function
> 781 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
      | ^  782 |
  783 | // Flag the module as loaded
  784 | module.l = true;
View compiled
fn
D:/CommuMind/front-react/webpack/bootstrap:149
  146 |         );
  147 |         hotCurrentParents = [];
  148 |     }
> 149 |     return __webpack_require__(request);
      | ^  150 | };
  151 | var ObjectFactory = function ObjectFactory(name) {
  152 |     return {
View compiled
Module../src/pages/draw/DrawPage.js
http://localhost:3000/static/js/main.chunk.js:335:77
__webpack_require__
D:/CommuMind/front-react/webpack/bootstrap:781
  778 | };
  779 |
  780 | // Execute the module function
> 781 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
      | ^  782 |
  783 | // Flag the module as loaded
  784 | module.l = true;
View compiled
fn
D:/CommuMind/front-react/webpack/bootstrap:149
  146 |         );
  147 |         hotCurrentParents = [];
  148 |     }
> 149 |     return __webpack_require__(request);
      | ^  150 | };
  151 | var ObjectFactory = function ObjectFactory(name) {
  152 |     return {
View compiled
Module../src/App.js
http://localhost:3000/static/js/main.chunk.js:145:78
__webpack_require__
D:/CommuMind/front-react/webpack/bootstrap:781
  778 | };
  779 |
  780 | // Execute the module function
> 781 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
      | ^  782 |
  783 | // Flag the module as loaded
  784 | module.l = true;
View compiled
fn
D:/CommuMind/front-react/webpack/bootstrap:149
  146 |         );
  147 |         hotCurrentParents = [];
  148 |     }
> 149 |     return __webpack_require__(request);
      | ^  150 | };
  151 | var ObjectFactory = function ObjectFactory(name) {
  152 |     return {
View compiled
Module../src/index.js
http://localhost:3000/static/js/main.chunk.js:247:62
__webpack_require__
D:/CommuMind/front-react/webpack/bootstrap:781
  778 | };
  779 |
  780 | // Execute the module function
> 781 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
      | ^  782 |
  783 | // Flag the module as loaded
  784 | module.l = true;
View compiled
fn
D:/CommuMind/front-react/webpack/bootstrap:149
  146 |         );
  147 |         hotCurrentParents = [];
  148 |     }
> 149 |     return __webpack_require__(request);
      | ^  150 | };
  151 | var ObjectFactory = function ObjectFactory(name) {
  152 |     return {
View compiled
0
http://localhost:3000/static/js/main.chunk.js:734:18
__webpack_require__
D:/CommuMind/front-react/webpack/bootstrap:781
  778 | };
  779 |
  780 | // Execute the module function
> 781 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
      | ^  782 |
  783 | // Flag the module as loaded
  784 | module.l = true;
View compiled
checkDeferredModules
D:/CommuMind/front-react/webpack/bootstrap:45
  42 |  }
  43 |  if(fulfilled) {
  44 |      deferredModules.splice(i--, 1);
> 45 |      result = __webpack_require__(__webpack_require__.s = deferredModule[0]);
     | ^  46 |  }
  47 | }
  48 | return result;
View compiled
Array.webpackJsonpCallback [as push]
D:/CommuMind/front-react/webpack/bootstrap:32
  29 |  deferredModules.push.apply(deferredModules, executeModules || []);
  30 |
  31 |  // run deferred modules when all chunks ready
> 32 |  return checkDeferredModules();
     | ^  33 | };
  34 | function checkDeferredModules() {
  35 |  var result;
View compiled
(anonymous function)
http://localhost:3000/static/js/main.chunk.js:1:57
</code>```

What went wrong???

答:
It looks like you have a circular dependency:

Someone imports DrawArea.js

At line 2, DrawArea.js imports DrawReflects.js

At line 2, DrawReflects.js wants to import DrawToolContext from DrawArea.js but it doesn't exists yet.

This messes with webpack and throws the error.

You can try to move the following line to another file "DrawToolContext.js"

```<code>export const DrawToolContext = React.createContext();
</code>```

This way, both DrawArea.js and DrawReflects.js can import it, without circular dependencies.

Body:
I want to make a simple React Web Application using Context API. I want to initialize context object in parent component, and want to use it in child component using "class.contextType".

I have read the link.

And I tried to code like below:

DrawArea.js // parent component which holds context provider and a child component

import React, {Component} from "react";
import DrawReflect from "./DrawReflect";
import "./DrawArea.css";

export const DrawToolContext = React.createContext();

class DrawArea extends Component{

    constructor(props){
        super(props);

        this.state = {
            drawTool: "line"
        };

    }

    render(){
        return (

                <DrawToolContext.Provider value={this.state}>

                        <DrawReflect />

                </DrawToolContext.Provider>

        );
    }
}

export default DrawArea;

DrawReflect.js // child component which adopts context from DrawArea and use it

import React, {Component} from "react";
import {DrawToolContext} from "./DrawArea";
import "./DrawReflect.css";

class DrawReflect extends Component{

    render(){
        return (

test

        );
    }

}

DrawReflect.contextType = DrawToolContext;

export default DrawReflect;

But it returns errors saying -
ReferenceError: Cannot access 'DrawToolContext' before initialization.

This is the full error stack:

Module.DrawToolContext
http://localhost:3000/static/js/main.chunk.js:473:107
Module../src/pages/draw/fragments/DrawReflect.js
D:/CommuMind/front-react/src/pages/draw/fragments/DrawReflect.js:17
  14 |
  15 | }
  16 |
> 17 | DrawReflect.contextType = DrawToolContext;
  18 |
  19 | export default DrawReflect;
View compiled
__webpack_require__
D:/CommuMind/front-react/webpack/bootstrap:781
  778 | };
  779 |
  780 | // Execute the module function
> 781 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
      | ^  782 |
  783 | // Flag the module as loaded
  784 | module.l = true;
View compiled
fn
D:/CommuMind/front-react/webpack/bootstrap:149
  146 |         );
  147 |         hotCurrentParents = [];
  148 |     }
> 149 |     return __webpack_require__(request);
      | ^  150 | };
  151 | var ObjectFactory = function ObjectFactory(name) {
  152 |     return {
View compiled
Module../src/pages/draw/fragments/DrawArea.js
http://localhost:3000/static/js/main.chunk.js:476:70
__webpack_require__
D:/CommuMind/front-react/webpack/bootstrap:781
  778 | };
  779 |
  780 | // Execute the module function
> 781 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
      | ^  782 |
  783 | // Flag the module as loaded
  784 | module.l = true;
View compiled
fn
D:/CommuMind/front-react/webpack/bootstrap:149
  146 |         );
  147 |         hotCurrentParents = [];
  148 |     }
> 149 |     return __webpack_require__(request);
      | ^  150 | };
  151 | var ObjectFactory = function ObjectFactory(name) {
  152 |     return {
View compiled
Module../src/pages/draw/DrawPage.js
http://localhost:3000/static/js/main.chunk.js:335:77
__webpack_require__
D:/CommuMind/front-react/webpack/bootstrap:781
  778 | };
  779 |
  780 | // Execute the module function
> 781 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
      | ^  782 |
  783 | // Flag the module as loaded
  784 | module.l = true;
View compiled
fn
D:/CommuMind/front-react/webpack/bootstrap:149
  146 |         );
  147 |         hotCurrentParents = [];
  148 |     }
> 149 |     return __webpack_require__(request);
      | ^  150 | };
  151 | var ObjectFactory = function ObjectFactory(name) {
  152 |     return {
View compiled
Module../src/App.js
http://localhost:3000/static/js/main.chunk.js:145:78
__webpack_require__
D:/CommuMind/front-react/webpack/bootstrap:781
  778 | };
  779 |
  780 | // Execute the module function
> 781 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
      | ^  782 |
  783 | // Flag the module as loaded
  784 | module.l = true;
View compiled
fn
D:/CommuMind/front-react/webpack/bootstrap:149
  146 |         );
  147 |         hotCurrentParents = [];
  148 |     }
> 149 |     return __webpack_require__(request);
      | ^  150 | };
  151 | var ObjectFactory = function ObjectFactory(name) {
  152 |     return {
View compiled
Module../src/index.js
http://localhost:3000/static/js/main.chunk.js:247:62
__webpack_require__
D:/CommuMind/front-react/webpack/bootstrap:781
  778 | };
  779 |
  780 | // Execute the module function
> 781 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
      | ^  782 |
  783 | // Flag the module as loaded
  784 | module.l = true;
View compiled
fn
D:/CommuMind/front-react/webpack/bootstrap:149
  146 |         );
  147 |         hotCurrentParents = [];
  148 |     }
> 149 |     return __webpack_require__(request);
      | ^  150 | };
  151 | var ObjectFactory = function ObjectFactory(name) {
  152 |     return {
View compiled
0
http://localhost:3000/static/js/main.chunk.js:734:18
__webpack_require__
D:/CommuMind/front-react/webpack/bootstrap:781
  778 | };
  779 |
  780 | // Execute the module function
> 781 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
      | ^  782 |
  783 | // Flag the module as loaded
  784 | module.l = true;
View compiled
checkDeferredModules
D:/CommuMind/front-react/webpack/bootstrap:45
  42 |  }
  43 |  if(fulfilled) {
  44 |      deferredModules.splice(i--, 1);
> 45 |      result = __webpack_require__(__webpack_require__.s = deferredModule[0]);
     | ^  46 |  }
  47 | }
  48 | return result;
View compiled
Array.webpackJsonpCallback [as push]
D:/CommuMind/front-react/webpack/bootstrap:32
  29 |  deferredModules.push.apply(deferredModules, executeModules || []);
  30 |
  31 |  // run deferred modules when all chunks ready
> 32 |  return checkDeferredModules();
     | ^  33 | };
  34 | function checkDeferredModules() {
  35 |  var result;
View compiled
(anonymous function)
http://localhost:3000/static/js/main.chunk.js:1:57

What went wrong???

Body:
It looks like you have a circular dependency:

Someone imports DrawArea.js

At line 2, DrawArea.js imports DrawReflects.js

At line 2, DrawReflects.js wants to import DrawToolContext from DrawArea.js but it doesn't exists yet.

This messes with webpack and throws the error.

You can try to move the following line to another file "DrawToolContext.js"

export const DrawToolContext = React.createContext();

This way, both DrawArea.js and DrawReflects.js can import it, without circular dependencies.


问:
RXJava Range gave me error of Type inference failed
While reading a book on RXJAVA, I am getting this error:

Type inference failed. Expected type mismatch: inferred type is
  Observable! but Observable was expected

From this simple snippet:

```<code>@Test
    fun deferable() {
       val source= Observable.range(1, 5)
                source.subscribe { s -> System.out.println("RECEIVED: $s "}
    }
</code>```

I do not get I am  why when I run the test I get this strange message. During my daily activities I manage this kind of error changing the return of the variable/property (the expression type)
as val source :Observable<Int>

but does not work, also I tried to do something as map{it.toString()}
but without success, how can I achieve to make the "test" pass? I know is not a real test I am using it only to learn RXJAVA, so there are no assertions, what I expect is to see this output:

```<code>RECEIVED:5
RECEIVED:6
RECEIVED:7
RECEIVED:8
RECEIVED:9
RECEIVED:10
RECEIVED:11
RECEIVED:12
RECEIVED:13
RECEIVED:14
</code>```

答:
Type inference failed. Expected type mismatch: inferred type is Observable! but Observable was expected

If you have such kind of compiler error, that means you are trying to pass nullable value instead of nonNull. You see the screamer: Observable! sign? This is the matter.

PS. test is green on my computer. Output is next:

```<code>RECEIVED: 1
RECEIVED: 2
RECEIVED: 3
RECEIVED: 4
RECEIVED: 5
</code>```

Body:
While reading a book on RXJAVA, I am getting this error:

Type inference failed. Expected type mismatch: inferred type is
  Observable! but Observable was expected

From this simple snippet:

@Test
    fun deferable() {
       val source= Observable.range(1, 5)
                source.subscribe { s -> System.out.println("RECEIVED: $s "}
    }

I do not get I am  why when I run the test I get this strange message. During my daily activities I manage this kind of error changing the return of the variable/property (the expression type)
as val source :Observable<Int>

but does not work, also I tried to do something as map{it.toString()}
but without success, how can I achieve to make the "test" pass? I know is not a real test I am using it only to learn RXJAVA, so there are no assertions, what I expect is to see this output:

RECEIVED:5
RECEIVED:6
RECEIVED:7
RECEIVED:8
RECEIVED:9
RECEIVED:10
RECEIVED:11
RECEIVED:12
RECEIVED:13
RECEIVED:14

Body:
Type inference failed. Expected type mismatch: inferred type is Observable! but Observable was expected

If you have such kind of compiler error, that means you are trying to pass nullable value instead of nonNull. You see the screamer: Observable! sign? This is the matter.

PS. test is green on my computer. Output is next:

RECEIVED: 1
RECEIVED: 2
RECEIVED: 3
RECEIVED: 4
RECEIVED: 5


问:
what is wrong with this code to obtain some statistics after lapply() in R
My data is something like this:

```<code>ind1 <- rnorm(99)
ind2 <- rnorm(99)
ind3 <- rnorm(99)
ind4 <- rnorm(99)
ind5 <- rnorm(99)
dep <- rnorm(99, mean=ind1)
group <- rep(c("A", "B", "C"), each=33)
df <- data.frame(dep,group, ind1, ind2, ind3, ind4, ind5)
head(df)

         dep group        ind1       ind2       ind3       ind4          ind5
1 -3.4471651     A -1.61903503  0.8047651 -0.1498872 -0.1421423  0.0003106164
2  1.6097232     A -0.07202246 -1.7419735 -0.4600787 -0.8966089  0.5476866447
3  0.2419204     A  0.37266251  1.1456788  0.2693086 -0.7610068 -0.6588102710
4  0.4157412     A  1.17342107  0.4829935  1.5044331  0.4902491 -0.1845711119
5 -1.1026655     A  0.31428775  0.9488747  0.1806105  0.4187126 -0.4420550339
6  1.9605406     A  1.36719867  1.1116940  0.7026870  0.6450296 -1.0824261091
</code>```

The next lines of code intend to run linear model for all possible combination of independent variables in the dataframe.

After selecting the significant models by p < 0.05 and ranking them by AIC value, I want to get following outputs: equation, estimate, R2, adj.R2, P value, AIC.

I tried it this way but the outputs are different from what I wanted. Does anyone have any idea to get them right?

```<code> indvar_list <- lapply(1:5, function(x)
   combn(paste0("ind", 1:5), x, , simplify = FALSE))

 formulas_list <- rapply(indvar_list, function(x)
   as.formula(paste("dep ~", paste(x, collapse="+"))))

 mult.lm <- lapply(formulas_list, function(x) glance(lm(as.formula(x),
 data = df)))

 outputs <- bind_rows(mult.lm, .id = 'index') %>%
   filter(p.value < 0.05) %>%
   arrange(AIC) %>%
   filter(index %in% head(unique(index)))
</code>```

thanks in advance!

答:
It looks like all you're missing is the equation and estimate? The rest seems like it's exactly what you want. I think the issue is you're using "glance" which doesn't return these variables. I typically use summary when trying to get information from my model, but that doesn't include AIC. It's also not very clean to get at. You can add a second and third mult.lm which contain the estimates and our coefficient names used in the model, pasted together for simplicity.

```<code>mult.lm_est <- lapply(formulas_list, function(x) paste(summary(lm(as.formula(x),
                                                       data = df))$coefficients[,1], collapse = ","))

mult.lm_coef <- lapply(formulas_list, function(x) paste(rownames(summary(lm(as.formula(x),
                                                       data = df))$coefficients), collapse = ","))
</code>```

Then you can bind rows on those lists as you did on your original, which will allow you to use dplyr joins by index

Body:
My data is something like this:

ind1 <- rnorm(99)
ind2 <- rnorm(99)
ind3 <- rnorm(99)
ind4 <- rnorm(99)
ind5 <- rnorm(99)
dep <- rnorm(99, mean=ind1)
group <- rep(c("A", "B", "C"), each=33)
df <- data.frame(dep,group, ind1, ind2, ind3, ind4, ind5)
head(df)

         dep group        ind1       ind2       ind3       ind4          ind5
1 -3.4471651     A -1.61903503  0.8047651 -0.1498872 -0.1421423  0.0003106164
2  1.6097232     A -0.07202246 -1.7419735 -0.4600787 -0.8966089  0.5476866447
3  0.2419204     A  0.37266251  1.1456788  0.2693086 -0.7610068 -0.6588102710
4  0.4157412     A  1.17342107  0.4829935  1.5044331  0.4902491 -0.1845711119
5 -1.1026655     A  0.31428775  0.9488747  0.1806105  0.4187126 -0.4420550339
6  1.9605406     A  1.36719867  1.1116940  0.7026870  0.6450296 -1.0824261091

The next lines of code intend to run linear model for all possible combination of independent variables in the dataframe.

After selecting the significant models by p < 0.05 and ranking them by AIC value, I want to get following outputs: equation, estimate, R2, adj.R2, P value, AIC.

I tried it this way but the outputs are different from what I wanted. Does anyone have any idea to get them right?

 indvar_list <- lapply(1:5, function(x)
   combn(paste0("ind", 1:5), x, , simplify = FALSE))

 formulas_list <- rapply(indvar_list, function(x)
   as.formula(paste("dep ~", paste(x, collapse="+"))))

 mult.lm <- lapply(formulas_list, function(x) glance(lm(as.formula(x),
 data = df)))

 outputs <- bind_rows(mult.lm, .id = 'index') %>%
   filter(p.value < 0.05) %>%
   arrange(AIC) %>%
   filter(index %in% head(unique(index)))

thanks in advance!

Body:
It looks like all you're missing is the equation and estimate? The rest seems like it's exactly what you want. I think the issue is you're using "glance" which doesn't return these variables. I typically use summary when trying to get information from my model, but that doesn't include AIC. It's also not very clean to get at. You can add a second and third mult.lm which contain the estimates and our coefficient names used in the model, pasted together for simplicity.

mult.lm_est <- lapply(formulas_list, function(x) paste(summary(lm(as.formula(x),
                                                       data = df))$coefficients[,1], collapse = ","))

mult.lm_coef <- lapply(formulas_list, function(x) paste(rownames(summary(lm(as.formula(x),
                                                       data = df))$coefficients), collapse = ","))

Then you can bind rows on those lists as you did on your original, which will allow you to use dplyr joins by index


问:
How to get in Angular2 the offSetTop of an element without using jQuery
I'm trying to create a directive that will fadeIn a photo slowly when an element is made visible. To do so, my first idea is comparing the position of an item regarding to the top (also checking the height of the window). But I can find how to do that with Angular2.

This is my code so far:

```<code>import {Directive, ElementRef, Renderer} from 'angular2/core';

@Directive({
    selector: '[fadeInPhoto]',
    host: {
        '(window:scroll)': 'onScroll()'
    }
})
export class FadeInPhotoDirective{
    private scrollTop: number;
    private initialClass: string;
    constructor(private _el: ElementRef, private _renderer: Renderer){
        this.initialClass = 'thumbnail';
    }

    onScroll(){
        console.log('Photo top:', this._el);
    }
}
</code>```

But this._el doesn't seem to have any method or property that contains that information.

答:
Try to do it like this: </p>

```<code>import { Component, OnInit, HostListener, ViewChild } from '@angular/core';

    @ViewChild("pageMenu")
      menuStickyElement;

     @HostListener("window:scroll", [])
      sticklyMenu() {
        // Get top height
        this. offsetTop = document.documentElement.scrollTop
        if (document.documentElement.scrollTop >= this.menuStickyElement.nativeElement.offsetTop) {
          this.stickyNavMenu = true;
        } else {
          this.stickyNavMenu = false;
        }
      }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to create a directive that will fadeIn a photo slowly when an element is made visible. To do so, my first idea is comparing the position of an item regarding to the top (also checking the height of the window). But I can find how to do that with Angular2.

This is my code so far:

import {Directive, ElementRef, Renderer} from 'angular2/core';

@Directive({
    selector: '[fadeInPhoto]',
    host: {
        '(window:scroll)': 'onScroll()'
    }
})
export class FadeInPhotoDirective{
    private scrollTop: number;
    private initialClass: string;
    constructor(private _el: ElementRef, private _renderer: Renderer){
        this.initialClass = 'thumbnail';
    }

    onScroll(){
        console.log('Photo top:', this._el);
    }
}

But this._el doesn't seem to have any method or property that contains that information.

Body:
Try to do it like this:

import { Component, OnInit, HostListener, ViewChild } from '@angular/core';

    @ViewChild("pageMenu")
      menuStickyElement;

     @HostListener("window:scroll", [])
      sticklyMenu() {
        // Get top height
        this. offsetTop = document.documentElement.scrollTop
        if (document.documentElement.scrollTop >= this.menuStickyElement.nativeElement.offsetTop) {
          this.stickyNavMenu = true;
        } else {
          this.stickyNavMenu = false;
        }
      }


问:
dateFromString always returns null with dateformatter
I have the following code:

```<code> NSDateFormatter * df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    [df setTimeZone:[NSTimeZone systemTimeZone]];
    [df setFormatterBehavior:NSDateFormatterBehaviorDefault];

    [df dateFromString:@"2011-04-12 10:00:00"];
</code>```

In which it always generates a null date. Why is this?

答:
Are you doing this in a background thread? I had weird experiences with NSDateFormatter when not being used in the ui-thread. Anyway, here's the method I use, should work for you:</p>

```<code>+ (NSDate*)parseDate:(NSString*)inStrDate format:(NSString*)inFormat {
    NSDateFormatter* dtFormatter = [[NSDateFormatter alloc] init];
    [dtFormatter setLocale:[NSLocale systemLocale]];
    [dtFormatter setDateFormat:inFormat];
    NSDate* dateOutput = [dtFormatter dateFromString:inStrDate];
    [dtFormatter release];
    return dateOutput;
}
</code>```

Body:
I have the following code:

 NSDateFormatter * df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    [df setTimeZone:[NSTimeZone systemTimeZone]];
    [df setFormatterBehavior:NSDateFormatterBehaviorDefault];

    [df dateFromString:@"2011-04-12 10:00:00"];

In which it always generates a null date. Why is this?

Body:
Are you doing this in a background thread? I had weird experiences with NSDateFormatter when not being used in the ui-thread. Anyway, here's the method I use, should work for you:

+ (NSDate*)parseDate:(NSString*)inStrDate format:(NSString*)inFormat {
    NSDateFormatter* dtFormatter = [[NSDateFormatter alloc] init];
    [dtFormatter setLocale:[NSLocale systemLocale]];
    [dtFormatter setDateFormat:inFormat];
    NSDate* dateOutput = [dtFormatter dateFromString:inStrDate];
    [dtFormatter release];
    return dateOutput;
}


问:
Need help to tune a complex query
I am trying to performance tune a query and need help with that

We have a requirement to pull in data on the website based on multiple factors which resulted in a complex query which works fine but is expensive. We have all the correct indexes.

What I am stuck on is removing the use of DISTINCT in the query (which seems to be the bottleneck).

I am no SQL expert and I think I've tried everything I could.

Any help to simplify this query and remove DISTINCT (or not use GROUP BY) will be much appreciated.  Thanks.

```<code>SELECT DISTINCT  t2.PK
FROM categories t0
    JOIN cat2catrel t1 ON  t1.SourcePK  =  t0.PK
    JOIN categories t2 ON  t1.TargetPK  =  t2.PK
    JOIN cat2catrel t3 ON  t3.SourcePK  =  t2.PK
    JOIN categories t4 ON  t3.TargetPK  =  t4.PK
    JOIN cat2prodrel t5 ON  t5.SourcePK = t4.PK
    JOIN products t6 ON  t5.TargetPK  =  t6.PK
    JOIN stocklevels t7 ON  t7.productcode  =  t6.code
    JOIN relativeinventory t8 ON  t7.p_inventory  =  t8.PK
    JOIN warehouses t9 ON  t7.warehouse  =  t9.PK
    JOIN pos2warehouserel t10 ON  t10.TargetPK  =  t9.PK
    JOIN pos2warehouserel t10 ON  t10.TargetPK  =  t9.PK
    JOIN pointofservice item_t11 ON  t10.SourcePK  =  t11.PK
    WHERE  ( t0.code  = 'code'
        AND  t8.nventorystatus  IN (1111)
        AND  t11.name  = 'ABC')
        AND ((t0.TypePkString IN  (1, 2, 3, 4)
        AND (( t0.catalogversion  IN (1, 2, 3)))
        AND t1.TypePkString=1000
        AND t2.TypePkString IN  (1, 2, 3, 4)
        AND (( t2.catalogversion  IN (1, 2)))
        AND t3.TypePkString=300
        AND t4.TypePkString IN  (6, 7, 8)
        AND (( t4.catalogversion  IN (5, 6)))
        AND t5.TypePkString=500
        AND t6.TypePkString=600
        AND t7.TypePkString=200
        AND t8.TypePkString=700
        AND t9.TypePkString IN  (3, 7)
        AND t10.TypePkString=900
        AND t11.TypePkString=750 ));
</code>```

Currently, this query works fine and provides the results I want.  I just don't want to use DISTINCT or GROUP BY and still get unique results.

DB:  MySQL 6.3

答:
Your only selecting t2.pk, which appears to be the primary key in the categories table. If this is correct, your producing duplication with your Joins. The easiest solution in general to get rid of DISTINCT in this scenario is to start with the table that you are selecting from and ensuring your INNER JOINING to it. However, it appears your actually doing this already, but your duplicating the join... i.e. t0 and t2 are the same table which is a big red flag to me. Try something like this:

```<code>SELECT t0.PK
FROM categories t0
    INNER JOIN cat2catrel t1 ON  t1.SourcePK  =  t0.PK AND t1.TargetPK = t0.PK
    INNER JOIN cat2catrel t3 ON  t3.SourcePK  =  t0.PK
    INNER JOIN categories t4 ON  t3.TargetPK  =  t4.PK
    INNER JOIN cat2prodrel t5 ON  t5.SourcePK = t4.PK
    INNER JOIN products t6 ON  t5.TargetPK  =  t6.PK
    INNER JOIN stocklevels t7 ON  t7.productcode  =  t6.code
    INNER JOIN relativeinventory t8 ON  t7.p_inventory  =  t8.PK
    INNER JOIN warehouses t9 ON  t7.warehouse  =  t9.PK
    INNER JOIN pos2warehouserel t10 ON  t10.TargetPK  =  t9.PK
    INNER JOIN pos2warehouserel t10 ON  t10.TargetPK  =  t9.PK
    INNER JOIN pointofservice item_t11 ON  t10.SourcePK  =  t11.PK
    WHERE  ( t0.code  = 'code'
        AND  t8.nventorystatus  IN (1111)
        AND  t11.name  = 'ABC')
        AND ((t0.TypePkString IN  (1, 2, 3, 4)
        AND (( t0.catalogversion  IN (1, 2, 3)))
        AND t1.TypePkString=1000
        AND t2.TypePkString IN  (1, 2, 3, 4)
        AND (( t2.catalogversion  IN (1, 2)))
        AND t3.TypePkString=300
        AND t4.TypePkString IN  (6, 7, 8)
        AND (( t4.catalogversion  IN (5, 6)))
        AND t5.TypePkString=500
        AND t6.TypePkString=600
        AND t7.TypePkString=200
        AND t8.TypePkString=700
        AND t9.TypePkString IN  (3, 7)
        AND t10.TypePkString=900
        AND t11.TypePkString=750 ));
</code>```

However I see other tables duplicated to like "pos2warehouserel". Tables should only be declared and assigned an alias once.

Title: Need help to tune a complex query

Body:
I am trying to performance tune a query and need help with that

We have a requirement to pull in data on the website based on multiple factors which resulted in a complex query which works fine but is expensive. We have all the correct indexes.

What I am stuck on is removing the use of DISTINCT in the query (which seems to be the bottleneck).

I am no SQL expert and I think I've tried everything I could.

Any help to simplify this query and remove DISTINCT (or not use GROUP BY) will be much appreciated.  Thanks.

SELECT DISTINCT  t2.PK
FROM categories t0
    JOIN cat2catrel t1 ON  t1.SourcePK  =  t0.PK
    JOIN categories t2 ON  t1.TargetPK  =  t2.PK
    JOIN cat2catrel t3 ON  t3.SourcePK  =  t2.PK
    JOIN categories t4 ON  t3.TargetPK  =  t4.PK
    JOIN cat2prodrel t5 ON  t5.SourcePK = t4.PK
    JOIN products t6 ON  t5.TargetPK  =  t6.PK
    JOIN stocklevels t7 ON  t7.productcode  =  t6.code
    JOIN relativeinventory t8 ON  t7.p_inventory  =  t8.PK
    JOIN warehouses t9 ON  t7.warehouse  =  t9.PK
    JOIN pos2warehouserel t10 ON  t10.TargetPK  =  t9.PK
    JOIN pos2warehouserel t10 ON  t10.TargetPK  =  t9.PK
    JOIN pointofservice item_t11 ON  t10.SourcePK  =  t11.PK
    WHERE  ( t0.code  = 'code'
        AND  t8.nventorystatus  IN (1111)
        AND  t11.name  = 'ABC')
        AND ((t0.TypePkString IN  (1, 2, 3, 4)
        AND (( t0.catalogversion  IN (1, 2, 3)))
        AND t1.TypePkString=1000
        AND t2.TypePkString IN  (1, 2, 3, 4)
        AND (( t2.catalogversion  IN (1, 2)))
        AND t3.TypePkString=300
        AND t4.TypePkString IN  (6, 7, 8)
        AND (( t4.catalogversion  IN (5, 6)))
        AND t5.TypePkString=500
        AND t6.TypePkString=600
        AND t7.TypePkString=200
        AND t8.TypePkString=700
        AND t9.TypePkString IN  (3, 7)
        AND t10.TypePkString=900
        AND t11.TypePkString=750 ));

Currently, this query works fine and provides the results I want.  I just don't want to use DISTINCT or GROUP BY and still get unique results.

DB:  MySQL 6.3

Body:
Your only selecting t2.pk, which appears to be the primary key in the categories table. If this is correct, your producing duplication with your Joins. The easiest solution in general to get rid of DISTINCT in this scenario is to start with the table that you are selecting from and ensuring your INNER JOINING to it. However, it appears your actually doing this already, but your duplicating the join... i.e. t0 and t2 are the same table which is a big red flag to me. Try something like this:

SELECT t0.PK
FROM categories t0
    INNER JOIN cat2catrel t1 ON  t1.SourcePK  =  t0.PK AND t1.TargetPK = t0.PK
    INNER JOIN cat2catrel t3 ON  t3.SourcePK  =  t0.PK
    INNER JOIN categories t4 ON  t3.TargetPK  =  t4.PK
    INNER JOIN cat2prodrel t5 ON  t5.SourcePK = t4.PK
    INNER JOIN products t6 ON  t5.TargetPK  =  t6.PK
    INNER JOIN stocklevels t7 ON  t7.productcode  =  t6.code
    INNER JOIN relativeinventory t8 ON  t7.p_inventory  =  t8.PK
    INNER JOIN warehouses t9 ON  t7.warehouse  =  t9.PK
    INNER JOIN pos2warehouserel t10 ON  t10.TargetPK  =  t9.PK
    INNER JOIN pos2warehouserel t10 ON  t10.TargetPK  =  t9.PK
    INNER JOIN pointofservice item_t11 ON  t10.SourcePK  =  t11.PK
    WHERE  ( t0.code  = 'code'
        AND  t8.nventorystatus  IN (1111)
        AND  t11.name  = 'ABC')
        AND ((t0.TypePkString IN  (1, 2, 3, 4)
        AND (( t0.catalogversion  IN (1, 2, 3)))
        AND t1.TypePkString=1000
        AND t2.TypePkString IN  (1, 2, 3, 4)
        AND (( t2.catalogversion  IN (1, 2)))
        AND t3.TypePkString=300
        AND t4.TypePkString IN  (6, 7, 8)
        AND (( t4.catalogversion  IN (5, 6)))
        AND t5.TypePkString=500
        AND t6.TypePkString=600
        AND t7.TypePkString=200
        AND t8.TypePkString=700
        AND t9.TypePkString IN  (3, 7)
        AND t10.TypePkString=900
        AND t11.TypePkString=750 ));

However I see other tables duplicated to like "pos2warehouserel". Tables should only be declared and assigned an alias once.


问:
Pandas sum-lag of a column
Lets say I have the data like this

```<code>df = pd.DataFrame({"MONTHS":[1,2,3,4,5,6], "METRIC":[430,584,648,571,610,535]})
</code>```

df = pd.DataFrame({"MONTHS":[1,2,3,4,5,6], "METRIC":[430,584,648,571,610,535]})
what I want to do is find the sum of the metric column =3378

```<code>MONTHS NEW_METRIC
 0       3378
 1       3378
 2       2948
 3       2794
 4       2730
 5       2807
 6       2768
</code>```

So here basically created a new row with 0 added and the corresponding new metric is the sum and for value 1 it is also the sum for new metric but from month=2 it should subtract the lag value of metric (3378-430) and similiarly for months3 it would be (3378-584) etc till the end.
As a first step I wanted to store the sum in result which failed

```<code>sum_METRIC = df.agg({"METRIC":"sum"}).collect()[0]
result = sum_METRIC["sum(METRIC)"]
</code>```

This threw error 'Series' object has no attribute 'collect'.

How do I sum and then use the lag to subtract?

Title: Pandas sum-lag of a column

Body:
Lets say I have the data like this

df = pd.DataFrame({"MONTHS":[1,2,3,4,5,6], "METRIC":[430,584,648,571,610,535]})

df = pd.DataFrame({"MONTHS":[1,2,3,4,5,6], "METRIC":[430,584,648,571,610,535]})
what I want to do is find the sum of the metric column =3378

MONTHS NEW_METRIC
 0       3378
 1       3378
 2       2948
 3       2794
 4       2730
 5       2807
 6       2768

So here basically created a new row with 0 added and the corresponding new metric is the sum and for value 1 it is also the sum for new metric but from month=2 it should subtract the lag value of metric (3378-430) and similiarly for months3 it would be (3378-584) etc till the end.
As a first step I wanted to store the sum in result which failed

sum_METRIC = df.agg({"METRIC":"sum"}).collect()[0]
result = sum_METRIC["sum(METRIC)"]

This threw error 'Series' object has no attribute 'collect'.

How do I sum and then use the lag to subtract?

Body:
Using

df['New']=df["METRIC"].sum() - np.array([0,0]+df["METRIC"].tolist())[:len(df)]
df
Out[307]:
   MONTHS  METRIC   New
0       1     430  3378
1       2     584  3378
2       3     648  2948
3       4     571  2794
4       5     610  2730
5       6     535  2807


问:
Generator not catching error from API call
I'm working with an API that doesn't return anything "error-like" for an incorrect login (just a normal object with a code -- incorrect_password or invalid_username -- an HTML message), so in my API calling function I'm turning the code into an error:

export async function loginWithApi(creds) {
  try {
    const res = await axios.get(ApiUrls.login, { params: creds });
    if (res.data.data) {
      return res.data;
    } else if (res.data.code) {
      throw Error(res.data.code.titleize());
    } // else, it should be an actual error
  } catch (err) {
    return err;
  }
}
```

<p>This works correctly, throws correctly, returns an Error when it should.</p>

<p>However, when testing my saga generator action that calls this function, the error isn't being caught, it's going unabated through the <code>try</code> block:</p>

<h3>function</h3>

<pre class="lang-js prettyprint-override"><code>export function* loginSaga({ username, password }) {
  const creds = { username, password };
  try {
    const res = yield call(loginWithApi, creds);
    console.log(res);
    yield put({ type: "LOGIN_SUCCESS", user: res.data });
  } catch (error) {
    yield put({ type: "LOGIN_FAILURE", error });
  }
}
</code>```

tests

 describe("login action", () => {
    let gen;
    afterEach(() => {
      expect(gen.next().done).toBe(true);
    });

    it("should return a user object on a successful login", () => {
      gen = loginSaga(success.creds);
      gen.next(); // call api
      expect(gen.next(mockResponse.success).value).toEqual(
        put({ type: "LOGIN_SUCCESS", user: mockResponse.success.data })
      );
    });

    it("should return an error when passed an invalid username", () => {
      gen = loginSaga(badUser.creds);
      gen.next(); // call api
      // mockReponse.usernameError: Error("Invalid Username")
      expect(gen.next(mockResponse.usernameError).value).toEqual(
        put({ type: "LOGIN_FAILURE", error: "Invalid Username" })
      );
    });

    it("should return an error when passed an invalid password", () => {
      gen = loginSaga(badPw.creds);
      gen.next(); // call api
      // mockResponse.passwordError: Error("Incorrect Password"),
      expect(gen.next(mockResponse.passwordError).value).toEqual(
        put({ type: "LOGIN_FAILURE", error: "Incorrect Password" })
      );
    });
  });
```

<h3>test output (excerpts)</h3>

<pre class="lang-js prettyprint-override"><code>  ● Saga Actions › login action › should return an error when passed an invalid username

    expect(received).toEqual(expected) // deep equality

    - Expected
    + Received

      Object {
        "@@redux-saga/IO": true,
        "combinator": false,
        "payload": Object {
          "action": Object {
    -       "error": "Invalid Username",
    -       "type": "LOGIN_FAILURE",
    +       "type": "LOGIN_SUCCESS",
    +       "user": undefined,
          },
          "channel": undefined,
        },
        "type": "PUT",

● Saga Actions › login action › should return an error when passed an invalid password

    expect(received).toEqual(expected) // deep equality

    - Expected
    + Received

      Object {
        "@@redux-saga/IO": true,
        "combinator": false,
        "payload": Object {
          "action": Object {
    -       "error": "Incorrect Password",
    -       "type": "LOGIN_FAILURE",
    +       "type": "LOGIN_SUCCESS",
    +       "user": undefined,
          },
          "channel": undefined,
        },
        "type": "PUT",
      }
</code>```

Logging confirms that the loginSaga function is receiving an Error in the second two tests. I can't quite determine why that error isn't being caught.

答:
Finally got it.

So you need make generator think that Exception happened for one of its yield. To make that we have generator.prototype.throw().

So next code should work as expected:

```<code>it("should return an error when passed an invalid username", () => {
  gen = loginSaga(badUser.creds);
  gen.next(); // call api
  // mockReponse.usernameError: Error("Invalid Username")
  expect(gen.throw(mockResponse.usernameError).value).toEqual(
    put({ type: "LOGIN_FAILURE", error: "Invalid Username" })
  );
});
</code>```

Body:
I'm working with an API that doesn't return anything "error-like" for an incorrect login (just a normal object with a code -- incorrect_password or invalid_username -- an HTML message), so in my API calling function I'm turning the code into an error:

export async function loginWithApi(creds) {
  try {
    const res = await axios.get(ApiUrls.login, { params: creds });
    if (res.data.data) {
      return res.data;
    } else if (res.data.code) {
      throw Error(res.data.code.titleize());
    } // else, it should be an actual error
  } catch (err) {
    return err;
  }
}

This works correctly, throws correctly, returns an Error when it should.

However, when testing my saga generator action that calls this function, the error isn't being caught, it's going unabated through the try block:

function

export function* loginSaga({ username, password }) {
  const creds = { username, password };
  try {
    const res = yield call(loginWithApi, creds);
    console.log(res);
    yield put({ type: "LOGIN_SUCCESS", user: res.data });
  } catch (error) {
    yield put({ type: "LOGIN_FAILURE", error });
  }
}

tests

 describe("login action", () => {
    let gen;
    afterEach(() => {
      expect(gen.next().done).toBe(true);
    });

    it("should return a user object on a successful login", () => {
      gen = loginSaga(success.creds);
      gen.next(); // call api
      expect(gen.next(mockResponse.success).value).toEqual(
        put({ type: "LOGIN_SUCCESS", user: mockResponse.success.data })
      );
    });

    it("should return an error when passed an invalid username", () => {
      gen = loginSaga(badUser.creds);
      gen.next(); // call api
      // mockReponse.usernameError: Error("Invalid Username")
      expect(gen.next(mockResponse.usernameError).value).toEqual(
        put({ type: "LOGIN_FAILURE", error: "Invalid Username" })
      );
    });

    it("should return an error when passed an invalid password", () => {
      gen = loginSaga(badPw.creds);
      gen.next(); // call api
      // mockResponse.passwordError: Error("Incorrect Password"),
      expect(gen.next(mockResponse.passwordError).value).toEqual(
        put({ type: "LOGIN_FAILURE", error: "Incorrect Password" })
      );
    });
  });

test output (excerpts)

  ● Saga Actions › login action › should return an error when passed an invalid username

    expect(received).toEqual(expected) // deep equality

    - Expected
    + Received

      Object {
        "@@redux-saga/IO": true,
        "combinator": false,
        "payload": Object {
          "action": Object {
    -       "error": "Invalid Username",
    -       "type": "LOGIN_FAILURE",
    +       "type": "LOGIN_SUCCESS",
    +       "user": undefined,
          },
          "channel": undefined,
        },
        "type": "PUT",

● Saga Actions › login action › should return an error when passed an invalid password

    expect(received).toEqual(expected) // deep equality

    - Expected
    + Received

      Object {
        "@@redux-saga/IO": true,
        "combinator": false,
        "payload": Object {
          "action": Object {
    -       "error": "Incorrect Password",
    -       "type": "LOGIN_FAILURE",
    +       "type": "LOGIN_SUCCESS",
    +       "user": undefined,
          },
          "channel": undefined,
        },
        "type": "PUT",
      }

Logging confirms that the loginSaga function is receiving an Error in the second two tests. I can't quite determine why that error isn't being caught.

Body:
Finally got it.

So you need make generator think that Exception happened for one of its yield. To make that we have generator.prototype.throw().

So next code should work as expected:

it("should return an error when passed an invalid username", () => {
  gen = loginSaga(badUser.creds);
  gen.next(); // call api
  // mockReponse.usernameError: Error("Invalid Username")
  expect(gen.throw(mockResponse.usernameError).value).toEqual(
    put({ type: "LOGIN_FAILURE", error: "Invalid Username" })
  );
});


问:
Why is my timer not working on Unity whenever I stop clicking?
I am working on an Unity project and I need to count the time the user takes to make his next move.

Every object in the game moves by using the mouse and dragging it so whenever the user stops dragging the main object the timer should start and when the user drags the object again it should stop.

This is my script for the drag and the timer:

```<code>private float startPosX;
    private float startPosY;
    public bool isHeld;
    //private float distance = 10;
    private float stopTime;

private void OnMouseDrag()
{
        Vector2 mousePos = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
        Vector2 objectPos = Camera.main.ScreenToWorldPoint(mousePos);
        transform.position = objectPos;
}

void Update()
{
    if (isHeld) {
        OnMouseDrag();
    }
    if (Input.GetMouseButtonUp(0))
    {
        isHeld = false;
        Debug.Log(isHeld);
        stopTime += Time.deltaTime;
        string minutes = Mathf.Floor((stopTime % 3600) / 60).ToString("00");
        string seconds = (stopTime % 60).ToString("00");
        Debug.Log(minutes + ":" + seconds);
    }
}

private void OnMouseOver()
{
    if (Input.GetMouseButtonDown(0)) {
        isHeld = true;
        Debug.Log(isHeld);
    }
}
</code>```

}

My onMouseDrag() is the actual function used to drag the object and on onMouseOver detects if the mouse is actually over the object.
The timer is given by deltaTime and then I use string minutes and seconds to display it in a nicer way and see if it is working correctly but it is not. I do not know why this is not working and I need some help because I am new to unity and coding.

答:
There are a couple things here that are causing you issues or are going to cause issues.

Input.GetMouseButtonUp(0) returns true exactly once on the frame that the button release is detected in Update(). That being said, the code within if(Input.GetMouseButtonUp(0)) will only execute once on the frame that the mouse button is released. This is why you aren't seeing anything printed from Debug.Log or when you are, it's not correct.

Your usage of the modulo operator % is mathematically incorrect for the minutes portion of your code. Mathf.Floor(stopTime / 60).ToString("00") would get you minutes correctly.

I would suggest structuring it this way:

```<code>void Update()
{
    if (Input.GetMouseButton(0)) {
        isHeld = true;
    }
    else
    {
        isHeld = false;
        Debug.Log(isHeld);
        stopTime += Time.deltaTime;
        string minutes = Mathf.Floor(stopTime / 60).ToString("00");
        string seconds = (stopTime % 60).ToString("00");
        Debug.Log(minutes + ":" + seconds);
    }
}

private void OnMouseOver()
{
    if (isHeld) {
        Debug.Log(isHeld);
        OnMouseDrag();
    }
}
</code>```

Body:
I am working on an Unity project and I need to count the time the user takes to make his next move.

Every object in the game moves by using the mouse and dragging it so whenever the user stops dragging the main object the timer should start and when the user drags the object again it should stop.

This is my script for the drag and the timer:

private float startPosX;
    private float startPosY;
    public bool isHeld;
    //private float distance = 10;
    private float stopTime;

private void OnMouseDrag()
{
        Vector2 mousePos = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
        Vector2 objectPos = Camera.main.ScreenToWorldPoint(mousePos);
        transform.position = objectPos;
}

void Update()
{
    if (isHeld) {
        OnMouseDrag();
    }
    if (Input.GetMouseButtonUp(0))
    {
        isHeld = false;
        Debug.Log(isHeld);
        stopTime += Time.deltaTime;
        string minutes = Mathf.Floor((stopTime % 3600) / 60).ToString("00");
        string seconds = (stopTime % 60).ToString("00");
        Debug.Log(minutes + ":" + seconds);
    }
}

private void OnMouseOver()
{
    if (Input.GetMouseButtonDown(0)) {
        isHeld = true;
        Debug.Log(isHeld);
    }
}

}

My onMouseDrag() is the actual function used to drag the object and on onMouseOver detects if the mouse is actually over the object.
The timer is given by deltaTime and then I use string minutes and seconds to display it in a nicer way and see if it is working correctly but it is not. I do not know why this is not working and I need some help because I am new to unity and coding.

Body:
There are a couple things here that are causing you issues or are going to cause issues.

Input.GetMouseButtonUp(0) returns true exactly once on the frame that the button release is detected in Update(). That being said, the code within if(Input.GetMouseButtonUp(0)) will only execute once on the frame that the mouse button is released. This is why you aren't seeing anything printed from Debug.Log or when you are, it's not correct.

Your usage of the modulo operator % is mathematically incorrect for the minutes portion of your code. Mathf.Floor(stopTime / 60).ToString("00") would get you minutes correctly.

I would suggest structuring it this way:

void Update()
{
    if (Input.GetMouseButton(0)) {
        isHeld = true;
    }
    else
    {
        isHeld = false;
        Debug.Log(isHeld);
        stopTime += Time.deltaTime;
        string minutes = Mathf.Floor(stopTime / 60).ToString("00");
        string seconds = (stopTime % 60).ToString("00");
        Debug.Log(minutes + ":" + seconds);
    }
}

private void OnMouseOver()
{
    if (isHeld) {
        Debug.Log(isHeld);
        OnMouseDrag();
    }
}


问:
Raise custom Exception with arguments
I'm defining a custom Exception on a model in rails as kind of a wrapper Exception: (begin[code]rescue[raise custom exception]end)

When I raise the Exception, I'd like to pass it some info about a) the instance of the model whose internal functions raise the error, and b) the error that was caught.

This is going on an automated import method of a model that gets populated by POST request to from foreign datasource.

tldr; How can one pass arguments to an Exception, given that you define the Exception yourself? I have an initialize method on that Exception but the raise syntax seems to only accept an Exception class and message, no optional parameters that get passed into the instantiation process.

答:
TL;DR 7 years after this question, I believe the correct answer is:

class CustomException < StandardError
  attr_reader :extra
  def initialize(message=nil, extra: nil)
    super(message)
    @extra = extra
  end
end
# => nil
raise CustomException.new('some message', extra: "blupp")
```

<p>WARNING: you will get identical results with:</p>

```raise CustomException.new(extra: 'blupp'), 'some message'
```

<p>but that is because <code>Exception#exception(string)</code> does a <code>#rb_obj_clone</code> on <code>self</code>, and then calls <code>exc_initialize</code> (which does NOT call <code>CustomException#initialize</code>.  From error.c:</p>

<pre class="lang-c prettyprint-override"><code>static VALUE
exc_exception(int argc, VALUE *argv, VALUE self)
{
    VALUE exc;

    if (argc == 0) return self;
    if (argc == 1 && self == argv[0]) return self;
    exc = rb_obj_clone(self);
    exc_initialize(argc, argv, exc);

    return exc;
}
</code>```

In the latter example of #raise up above, a CustomException will be raised with message set to "a message" and extra set to "blupp" (because it is a clone) but TWO CustomException objects are actually created: the first by CustomException.new, and the second by #raise calling #exception on the first instance of CustomException which creates a second cloned CustomException.

My extended dance remix version of why is at: https://stackoverflow.com/a/56371923/5299483

Title: Raise custom Exception with arguments

Body:
TL;DR 7 years after this question, I believe the correct answer is:

class CustomException < StandardError
  attr_reader :extra
  def initialize(message=nil, extra: nil)
    super(message)
    @extra = extra
  end
end
# => nil
raise CustomException.new('some message', extra: "blupp")

WARNING: you will get identical results with:

raise CustomException.new(extra: 'blupp'), 'some message'

but that is because Exception#exception(string) does a #rb_obj_clone on self, and then calls exc_initialize (which does NOT call CustomException#initialize.  From error.c:

static VALUE
exc_exception(int argc, VALUE *argv, VALUE self)
{
    VALUE exc;

    if (argc == 0) return self;
    if (argc == 1 && self == argv[0]) return self;
    exc = rb_obj_clone(self);
    exc_initialize(argc, argv, exc);

    return exc;
}

In the latter example of #raise up above, a CustomException will be raised with message set to "a message" and extra set to "blupp" (because it is a clone) but TWO CustomException objects are actually created: the first by CustomException.new, and the second by #raise calling #exception on the first instance of CustomException which creates a second cloned CustomException.

My extended dance remix version of why is at: https://stackoverflow.com/a/56371923/5299483


问:
MongoDB weird behavior needs explanation
So yesterday I started messing around with MongoDB in Node and when it comes to retrieving data I encountered a weird practice.
You retrieve data from a collection that is nested within a database by calling.

```<code>data = client.db([dbname]).collection([collectionname]).find([searchcriteria])
</code>```

and this returns what seems to be an object at least in the eyes of typeof

the sample code then uses the following lines to log it to the console:

```<code>function iterate(x){
    console.log(x)
}
data.forEach(iterate)
</code>```

The output is as expected in this case two objects with 2 pairs everything is fine so far.

I thought it is a bit unnecessary to have the iterate function so I changed that to just

```<code>console.log(data)
</code>```

expecting the 2 objects in a array or nested in another object but what i get is this huge object with all kinds of different things in it EXCEPT the two objects that we saw before.

So now to my Question and what I need deeper explanation on:

why can i actually use .forEach() on this object I cannot recreate this on other objects.

and the second thing is why is console.log(data) giving me all this output that is hidden if I call it through .forEach()?

and is there any other way to quickly within one or 2 lines of code retrieve data from Mongo ?

this seems to be a very not useful way of doing things.
and how does this .forEach() thing on objects work I found a article here on stack however this was not very detailed and not very easy to understand.

答:
The find function returns a cursor - this is the huge object that you are seeing. Checkout documentation for more details here: https://docs.mongodb.com/manual/reference/method/db.collection.find/#db.collection.find

The reason why you can call forEach on the returned object (=cursor), is because it is one of its methods. See https://docs.mongodb.com/manual/reference/method/cursor.forEach/#cursor.forEach

Overview of all cursor methods is here: https://docs.mongodb.com/manual/reference/method/js-cursor/

To get the array of data that you are looking for you need to use the toArray method, like so:

```<code>const data = client.db([dbname]).collection([collectionname]).find([searchcriteria]).toArray()
</code>```

Body:
So yesterday I started messing around with MongoDB in Node and when it comes to retrieving data I encountered a weird practice.
You retrieve data from a collection that is nested within a database by calling.

data = client.db([dbname]).collection([collectionname]).find([searchcriteria])

and this returns what seems to be an object at least in the eyes of typeof

the sample code then uses the following lines to log it to the console:

function iterate(x){
    console.log(x)
}
data.forEach(iterate)

The output is as expected in this case two objects with 2 pairs everything is fine so far.

I thought it is a bit unnecessary to have the iterate function so I changed that to just

console.log(data)

expecting the 2 objects in a array or nested in another object but what i get is this huge object with all kinds of different things in it EXCEPT the two objects that we saw before.

So now to my Question and what I need deeper explanation on:

why can i actually use .forEach() on this object I cannot recreate this on other objects.

and the second thing is why is console.log(data) giving me all this output that is hidden if I call it through .forEach()?

and is there any other way to quickly within one or 2 lines of code retrieve data from Mongo ?

this seems to be a very not useful way of doing things.
and how does this .forEach() thing on objects work I found a article here on stack however this was not very detailed and not very easy to understand.

Body:
The find function returns a cursor - this is the huge object that you are seeing. Checkout documentation for more details here: https://docs.mongodb.com/manual/reference/method/db.collection.find/#db.collection.find

The reason why you can call forEach on the returned object (=cursor), is because it is one of its methods. See https://docs.mongodb.com/manual/reference/method/cursor.forEach/#cursor.forEach

Overview of all cursor methods is here: https://docs.mongodb.com/manual/reference/method/js-cursor/

To get the array of data that you are looking for you need to use the toArray method, like so:

const data = client.db([dbname]).collection([collectionname]).find([searchcriteria]).toArray()


问:
socket.io, io is not defined (JS Error)
I have just started with socket.io, its giving JS Error on client page

io is not defined

How to fix this ?

答:
Alternatively you can use the Socket.io CDN:</p>

```<code><script src="https://cdn.socket.io/socket.io-1.0.0.js"></script>
</code>```

Title: socket.io, io is not defined (JS Error)

Body:
Alternatively you can use the Socket.io CDN:

<script src="https://cdn.socket.io/socket.io-1.0.0.js"></script>