问:
Images Don't Display in Rshiny

images don't display correctly (empty image displays) in R shiny, both internal as external (app.R) runs

similar questions posted in the past on this site do not provide an adequate answer: the solution of running the application through app.R doesn't solve the problem for me, image still isn't displayed

in the code: image is added to the main panel , both tried from documents as from web (converting images to web link).

example image: https://ibb.co/Bt6v6W9

I tried both to include the image through documents (local working directory) as by converting the image to a web link.

how the output looks: https://cdn1.imggmi.com/uploads/2019/4/24/d65ae8a21decc6adb1d14db9a3e9bf75-full.png

Anyone an idea for solution?  As mentioned, running the application through app.R doesn't work, output remains the same.

```<code>    library(shiny)
    library(png)

    # See above for the definitions of ui and server
    library(shiny)
    library(png)

    # Define UI for app that draws a histogram ----
    ui <- fluidPage(

      # App title ----
      titlePanel("Hello Shiny!"),

      # Sidebar layout with input and output definitions ----
      sidebarLayout(

        # Sidebar panel for inputs ----
        sidebarPanel(

          # Input: Slider for the number of bins ----
          sliderInput(inputId = "bins",
                      label = "Number of bins:",
                      min = 1,
                      max = 50,
                      value = 30)

        ),

        # Main panel for displaying outputs ----
        mainPanel(

          # Output: Histogram ----

                plotOutput(outputId = "distPlot"),
          img(src='DataVIS1.png', align = "right",height=168,width=70)

          ##output: png image

        )
      )
    )

    server <- function(input, output) {

      # Histogram of the Old Faithful Geyser Data ----
      # with requested number of bins
      # This expression that generates a histogram is wrapped in a call
      # to renderPlot to indicate that:
      #
      # 1. It is "reactive" and therefore should be automatically
      #    re-executed when inputs (input$bins) change
      # 2. Its output type is a plot
      output$distPlot <- renderPlot({

        x    <- faithful$waiting
        bins <- seq(min(x), max(x), length.out = input$bins + 1)

        hist(x, breaks = bins, col = "#75AADB", border = "white",
             xlab = "Waiting time to next eruption (in mins)",
             main = "Histogram of waiting times")

      })

    }

    shinyApp(ui = ui, server = server

)
</code>```

答:
You should throw the code that creates the image in the server side, encapsulate it inside a a renderPlot({}) function that you've named, then plot the output just after the "distPlot" plotOutput. I couldn't get your img(src=...) code to work so I used a raster plot which is functionally the same for this purpose. A minified example is as follows:

```<code>library(shiny)
library(png)

ui <- fluidPage(
  mainPanel(
    plotOutput(outputId = "png")
  )
)

server <- function(input, output) {
  output$png <- renderPlot({
    pic = readPNG('path/to/image.png')
    plot.new()
    grid::grid.raster(pic)

  })
}

shinyApp(ui = ui, server = server)
</code>```

Putting this into your code yields:

```<code>library(shiny)
library(png)

# See above for the definitions of ui and server
library(shiny)
library(png)

# Define UI for app that draws a histogram ----
ui <- fluidPage(

  # App title ----
  titlePanel("Hello Shiny!"),

  # Sidebar layout with input and output definitions ----
  sidebarLayout(

    # Sidebar panel for inputs ----
    sidebarPanel(

      # Input: Slider for the number of bins ----
      sliderInput(inputId = "bins",
                  label = "Number of bins:",
                  min = 1,
                  max = 50,
                  value = 30)

    ),

    # Main panel for displaying outputs ----
    mainPanel(

      # Output: Histogram ----

      plotOutput(outputId = "distPlot"),
      ###Changed code here
      plotOutput(outputId = "png")

      ##output: png image

    )
  )
)

server <- function(input, output) {

  # Histogram of the Old Faithful Geyser Data ----
  # with requested number of bins
  # This expression that generates a histogram is wrapped in a call
  # to renderPlot to indicate that:
  #
  # 1. It is "reactive" and therefore should be automatically
  #    re-executed when inputs (input$bins) change
  # 2. Its output type is a plot
  output$distPlot <- renderPlot({

    x    <- faithful$waiting
    bins <- seq(min(x), max(x), length.out = input$bins + 1)

    hist(x, breaks = bins, col = "#75AADB", border = "white",
         xlab = "Waiting time to next eruption (in mins)",
         main = "Histogram of waiting times")

  })

  ###New function
  output$png <- renderPlot({
    pic = readPNG('path/to/image.png')
    plot.new()
    grid::grid.raster(pic)

  })

}

shinyApp(ui = ui, server = server

)
</code>```

... And displays:

Title: Images Don't Display in Rshiny

Body:
images don't display correctly (empty image displays) in R shiny, both internal as external (app.R) runs

similar questions posted in the past on this site do not provide an adequate answer: the solution of running the application through app.R doesn't solve the problem for me, image still isn't displayed

in the code: image is added to the main panel , both tried from documents as from web (converting images to web link).

example image: https://ibb.co/Bt6v6W9

I tried both to include the image through documents (local working directory) as by converting the image to a web link.

how the output looks: https://cdn1.imggmi.com/uploads/2019/4/24/d65ae8a21decc6adb1d14db9a3e9bf75-full.png

Anyone an idea for solution?  As mentioned, running the application through app.R doesn't work, output remains the same.

    library(shiny)
    library(png)

    # See above for the definitions of ui and server
    library(shiny)
    library(png)

    # Define UI for app that draws a histogram ----
    ui <- fluidPage(

      # App title ----
      titlePanel("Hello Shiny!"),

      # Sidebar layout with input and output definitions ----
      sidebarLayout(

        # Sidebar panel for inputs ----
        sidebarPanel(

          # Input: Slider for the number of bins ----
          sliderInput(inputId = "bins",
                      label = "Number of bins:",
                      min = 1,
                      max = 50,
                      value = 30)

        ),

        # Main panel for displaying outputs ----
        mainPanel(

          # Output: Histogram ----

                plotOutput(outputId = "distPlot"),
          img(src='DataVIS1.png', align = "right",height=168,width=70)

          ##output: png image

        )
      )
    )

    server <- function(input, output) {

      # Histogram of the Old Faithful Geyser Data ----
      # with requested number of bins
      # This expression that generates a histogram is wrapped in a call
      # to renderPlot to indicate that:
      #
      # 1. It is "reactive" and therefore should be automatically
      #    re-executed when inputs (input$bins) change
      # 2. Its output type is a plot
      output$distPlot <- renderPlot({

        x    <- faithful$waiting
        bins <- seq(min(x), max(x), length.out = input$bins + 1)

        hist(x, breaks = bins, col = "#75AADB", border = "white",
             xlab = "Waiting time to next eruption (in mins)",
             main = "Histogram of waiting times")

      })

    }

    shinyApp(ui = ui, server = server

)

Body:
You should throw the code that creates the image in the server side, encapsulate it inside a a renderPlot({}) function that you've named, then plot the output just after the "distPlot" plotOutput. I couldn't get your img(src=...) code to work so I used a raster plot which is functionally the same for this purpose. A minified example is as follows:

library(shiny)
library(png)

ui <- fluidPage(
  mainPanel(
    plotOutput(outputId = "png")
  )
)

server <- function(input, output) {
  output$png <- renderPlot({
    pic = readPNG('path/to/image.png')
    plot.new()
    grid::grid.raster(pic)

  })
}

shinyApp(ui = ui, server = server)

Putting this into your code yields:

library(shiny)
library(png)

# See above for the definitions of ui and server
library(shiny)
library(png)

# Define UI for app that draws a histogram ----
ui <- fluidPage(

  # App title ----
  titlePanel("Hello Shiny!"),

  # Sidebar layout with input and output definitions ----
  sidebarLayout(

    # Sidebar panel for inputs ----
    sidebarPanel(

      # Input: Slider for the number of bins ----
      sliderInput(inputId = "bins",
                  label = "Number of bins:",
                  min = 1,
                  max = 50,
                  value = 30)

    ),

    # Main panel for displaying outputs ----
    mainPanel(

      # Output: Histogram ----

      plotOutput(outputId = "distPlot"),
      ###Changed code here
      plotOutput(outputId = "png")

      ##output: png image

    )
  )
)

server <- function(input, output) {

  # Histogram of the Old Faithful Geyser Data ----
  # with requested number of bins
  # This expression that generates a histogram is wrapped in a call
  # to renderPlot to indicate that:
  #
  # 1. It is "reactive" and therefore should be automatically
  #    re-executed when inputs (input$bins) change
  # 2. Its output type is a plot
  output$distPlot <- renderPlot({

    x    <- faithful$waiting
    bins <- seq(min(x), max(x), length.out = input$bins + 1)

    hist(x, breaks = bins, col = "#75AADB", border = "white",
         xlab = "Waiting time to next eruption (in mins)",
         main = "Histogram of waiting times")

  })

  ###New function
  output$png <- renderPlot({
    pic = readPNG('path/to/image.png')
    plot.new()
    grid::grid.raster(pic)

  })

}

shinyApp(ui = ui, server = server

)

... And displays:


来源: stackexchange

问:
JPA - Returning an auto generated id after persist()
I'm using JPA (EclipseLink) and Spring. Say I have a simple entity with an auto-generated ID:

```<code>@Entity
public class ABC implements Serializable {
     @Id
     @GeneratedValue(strategy=GenerationType.IDENTITY)
     private int id;

     // ...
}
</code>```

In my DAO class, I have an insert method that calls persist() on this entity. I want the method to return the generated ID for the new entity, but when I test it, it returns 0 instead.

```<code>public class ABCDao {
    @PersistenceContext
    EntityManager em;

    @Transactional(readOnly=false)
    public int insertABC(ABC abc) {
         em.persist(abc);
         // I WANT TO RETURN THE AUTO-GENERATED ID OF abc
         // HOW CAN I DO IT?
         return abc.id; // ???
    }
}
</code>```

I also have a service class that wraps the DAO, if that makes a difference:

```<code>public class ABCService {
    @Resource(name="ABCDao")
    ABCDao abcDao;

    public int addNewABC(ABC abc) {
         return abcDao.insertABC(abc);
    }
}
</code>```

答:
This is how I did it. You can try</p>

```<code>    public class ABCService {
    @Resource(name="ABCDao")
    ABCDao abcDao;

    public int addNewABC(ABC abc) {
         ABC.setId(0);
         return abcDao.insertABC(abc);
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm using JPA (EclipseLink) and Spring. Say I have a simple entity with an auto-generated ID:

@Entity
public class ABC implements Serializable {
     @Id
     @GeneratedValue(strategy=GenerationType.IDENTITY)
     private int id;

     // ...
}

In my DAO class, I have an insert method that calls persist() on this entity. I want the method to return the generated ID for the new entity, but when I test it, it returns 0 instead.

public class ABCDao {
    @PersistenceContext
    EntityManager em;

    @Transactional(readOnly=false)
    public int insertABC(ABC abc) {
         em.persist(abc);
         // I WANT TO RETURN THE AUTO-GENERATED ID OF abc
         // HOW CAN I DO IT?
         return abc.id; // ???
    }
}

I also have a service class that wraps the DAO, if that makes a difference:

public class ABCService {
    @Resource(name="ABCDao")
    ABCDao abcDao;

    public int addNewABC(ABC abc) {
         return abcDao.insertABC(abc);
    }
}

Body:
This is how I did it. You can try

    public class ABCService {
    @Resource(name="ABCDao")
    ABCDao abcDao;

    public int addNewABC(ABC abc) {
         ABC.setId(0);
         return abcDao.insertABC(abc);
    }
}

ContentLicense: CC BY-SA 4.0


问:
How to fix blacksreen when changing resolution in Unity
I made a 2d game, which worked fine when I built it, but after I implemented a resolution change, it failed to render everything properly and only rendered the player.

I've tried removing these lines, but it hasn't helped. Every build after that has that resolution (I can see it being applied to the player) and fails to render the rest.

I use this at the start of the game.

```<code>Screen.SetResolution(160, 144, true, 60);
</code>```

I also got these, but I'm unsure if they are related.

```<code>Multiple managers are loaded of type: InputManager
Multiple managers are loaded of type: GraphicsSettings
Multiple managers are loaded of type: PhysicsManager
Multiple managers are loaded of type: QualitySettings
Multiple managers are loaded of type: Physics2DSettings
Multiple managers are loaded of type: VFXManager
</code>```

答:
Assuming you are using desktop:

To set a specific full-screen mode on a desktop platform, use the
  method overload that accepts the FullScreenMode parameter.

```<code>public static void SetResolution(int width, int height, FullScreenMode fullscreenMode, int preferredRefreshRate = 0);
</code>```

https://docs.unity3d.com/ScriptReference/Screen.SetResolution.html

The fullscreenMode parameter can be one of these types:

```<code>ExclusiveFullScreen
FullScreenWindow
MaximizedWindow
Windowed
</code>```

https://docs.unity3d.com/ScriptReference/FullScreenMode.html

i.e:

```<code>Screen.SetResolution(160, 144, FullScreenMode.ExclusiveFullscreen, 60);
</code>```

Body:
I made a 2d game, which worked fine when I built it, but after I implemented a resolution change, it failed to render everything properly and only rendered the player.

I've tried removing these lines, but it hasn't helped. Every build after that has that resolution (I can see it being applied to the player) and fails to render the rest.

I use this at the start of the game.

Screen.SetResolution(160, 144, true, 60);

I also got these, but I'm unsure if they are related.

Multiple managers are loaded of type: InputManager
Multiple managers are loaded of type: GraphicsSettings
Multiple managers are loaded of type: PhysicsManager
Multiple managers are loaded of type: QualitySettings
Multiple managers are loaded of type: Physics2DSettings
Multiple managers are loaded of type: VFXManager

Body:
Assuming you are using desktop:

To set a specific full-screen mode on a desktop platform, use the
  method overload that accepts the FullScreenMode parameter.

public static void SetResolution(int width, int height, FullScreenMode fullscreenMode, int preferredRefreshRate = 0);

https://docs.unity3d.com/ScriptReference/Screen.SetResolution.html

The fullscreenMode parameter can be one of these types:

ExclusiveFullScreen
FullScreenWindow
MaximizedWindow
Windowed

https://docs.unity3d.com/ScriptReference/FullScreenMode.html

i.e:

Screen.SetResolution(160, 144, FullScreenMode.ExclusiveFullscreen, 60);


问:
How to filter certain values of numbers from a string and return the rest
I need to create a method that takes a string as an input, like "I have 2456 balloons in 37 wilderness" and if n is set to 3 and "more" is set to false, the method would return "I have 2 balloons in wilderness". If more was set to true, it would return "I have 456 balloons in 7 wilderness"

I have been playing around with the filtering part quite a bit, but I don't know how to put the rest of this method together. Here is what I have come up with so far:

```<code>public class Test1
{
    public static void main(String [] args)
    {
        List<Integer> lst= new ArrayList<Integer>();
        //Take user input any number of times based on your condition.

        System.out.println("Please enter a number :");
        Scanner sc= new Scanner(System.in);
        int i= sc.nextInt();
        if(i==0 || i==1 || i==2 ||i==3)
        {
            lst.add(i);
        }
        //Go back
    }
}
</code>```

Or I could use something like this:

```<code>int input;
do {
    input = sc.nextInt();
} while (input < 0 || input > 3);
</code>```

I'm pretty new to Java, so progress on this task has been slow

How can I get this method to save the letters and filter numbers depending on the two values (a number and true/false for more)?

答:
Here is a simple solution with explanation.
Take note that we used a very straightforward approach but a lot of validations are still needed. Also, there are shorter solutions but this is the one I wrote so that it's clearer for people new in Java.</p>

```<code>public static void main(String[] args) {
    Scanner sc= new Scanner(System.in);

    System.out.println("Enter your string: ");
    String strInput = sc.nextLine();

    System.out.println("Enter n: ");
    int n = sc.nextInt();

    System.out.println("Do you want more? (Y/N)");
    char more = sc.next().charAt(0);

    String result = "";

    // Loop through all the characters in the String
    for(char c : strInput.toCharArray()) {

        // Check if the character is a number
        // If not, just append to our result string
        if(!Character.isDigit(c)) {
            result += c;
        } else {
            // Converts character to the number equivalent value
            int numValue = Character.getNumericValue(c);

            // If more is 'Y', we check if it's greater than the number and append
            // else if more is 'N', we check if the value is less than n then append.
            // Otherwise, do nothing.
            if (more == 'Y' && numValue > n) {
                result += c;
            } else if (more == 'N' && numValue < n) {
                result += c;
            }
        }
    }

    System.out.println(result);
}
</code>```

Body:
I need to create a method that takes a string as an input, like "I have 2456 balloons in 37 wilderness" and if n is set to 3 and "more" is set to false, the method would return "I have 2 balloons in wilderness". If more was set to true, it would return "I have 456 balloons in 7 wilderness"

I have been playing around with the filtering part quite a bit, but I don't know how to put the rest of this method together. Here is what I have come up with so far:

public class Test1
{
    public static void main(String [] args)
    {
        List<Integer> lst= new ArrayList<Integer>();
        //Take user input any number of times based on your condition.

        System.out.println("Please enter a number :");
        Scanner sc= new Scanner(System.in);
        int i= sc.nextInt();
        if(i==0 || i==1 || i==2 ||i==3)
        {
            lst.add(i);
        }
        //Go back
    }
}

Or I could use something like this:

int input;
do {
    input = sc.nextInt();
} while (input < 0 || input > 3);

I'm pretty new to Java, so progress on this task has been slow

How can I get this method to save the letters and filter numbers depending on the two values (a number and true/false for more)?

Body:
Here is a simple solution with explanation.
Take note that we used a very straightforward approach but a lot of validations are still needed. Also, there are shorter solutions but this is the one I wrote so that it's clearer for people new in Java.

public static void main(String[] args) {
    Scanner sc= new Scanner(System.in);

    System.out.println("Enter your string: ");
    String strInput = sc.nextLine();

    System.out.println("Enter n: ");
    int n = sc.nextInt();

    System.out.println("Do you want more? (Y/N)");
    char more = sc.next().charAt(0);

    String result = "";

    // Loop through all the characters in the String
    for(char c : strInput.toCharArray()) {

        // Check if the character is a number
        // If not, just append to our result string
        if(!Character.isDigit(c)) {
            result += c;
        } else {
            // Converts character to the number equivalent value
            int numValue = Character.getNumericValue(c);

            // If more is 'Y', we check if it's greater than the number and append
            // else if more is 'N', we check if the value is less than n then append.
            // Otherwise, do nothing.
            if (more == 'Y' && numValue > n) {
                result += c;
            } else if (more == 'N' && numValue < n) {
                result += c;
            }
        }
    }

    System.out.println(result);
}


问:
responsive web design video container whitespace
I am trying to make a responsive web site and the problem I am facing currently is that when I minimize the browser size, my background video leaves a chunk of whitespace. It does not fill the size of the header and the following div after that is displayed after the whitespace.

As far as getting rid of video-container and using 100vw and 100vh on video-bg, I have tried and it does not work because my video is zoomed in at that point and does not display the entirety of the video.

https://www.videezy.com/urban/3951-top-to-bottom-panning-shot-of-downtown-los-angeles-4k

The above link is to download the video I am using.

```<code><!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<style>
body {
    margin: 0;
    padding: 0;
}
#block {
    background-color: black;
    height: 500px;
}
.embed-container {
    position: relative;
    padding-bottom: 56.25%;
    height: 0; overflow:
    hidden;
    max-width: 100%;
}
.embed-container video, /*.embed-container object, .embed-container embed*/ {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}
</style>
<body>
<!DOCTYPE html>
<html>
    <head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" type="text/css" href="styles.css">
    </head>
    <body>
        <div class='embed-container'>
            <video autoplay muted allowfullscreen>
                <source src="downtownla.mp4" type="video/mp4">
            </video>
        </div>
        <div id="block">
            1
        </div>
    </body>
</html>
</body>
</html>
</code>```

My expected goal is to be able to have a video that is responsive and allows for the following div to be displayed immediately after without any whitespace.

答:
I think it will be all right now.

body {
  margin: 0;
}

.container-fluid .header {
  position: relative;
}

.video-container {
  z-index: -100;
  overflow: hidden;
  position: relative;
  top: 0;
  left: 0;
}

#video-bg {
  margin: 0 auto;
  width: 100%;
  min-width: 100vw;
  max-height: 100vh;
  height: 100%;
  display: block;
  object-fit: fill;
}

.block {
  width: 100%;
  height: 100vh;
}

#block1 {
  background: black;
}

#block2 {
  background: yellow;
}

#block3 {
  background: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container-fluid header">
  <div class="header">

    <div class="video-container">
      <video autoplay muted id="video-bg">

        <source src="https://static.videezy.com/system/resources/previews/000/003/951/original/downtownla.mp4" type="video/mp4"/>

      </video>
    </div>
  </div>
</div>

<div id="block1" class="block">

</div>
<div id="block2" class="block">

</div>
<div id="block3" class="block">

</div></code>```

Body:
I am trying to make a responsive web site and the problem I am facing currently is that when I minimize the browser size, my background video leaves a chunk of whitespace. It does not fill the size of the header and the following div after that is displayed after the whitespace.

As far as getting rid of video-container and using 100vw and 100vh on video-bg, I have tried and it does not work because my video is zoomed in at that point and does not display the entirety of the video.

https://www.videezy.com/urban/3951-top-to-bottom-panning-shot-of-downtown-los-angeles-4k

The above link is to download the video I am using.

<!DOCTYPE html>

    <title></title>

<!DOCTYPE html>

    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" type="text/css" href="styles.css">

            <video autoplay muted allowfullscreen>
                <source src="downtownla.mp4" type="video/mp4">
            </video>

            1

My expected goal is to be able to have a video that is responsive and allows for the following div to be displayed immediately after without any whitespace.

Body:
I think it will be all right now.

body {
  margin: 0;
}

.container-fluid .header {
  position: relative;
}

.video-container {
  z-index: -100;
  overflow: hidden;
  position: relative;
  top: 0;
  left: 0;
}

#video-bg {
  margin: 0 auto;
  width: 100%;
  min-width: 100vw;
  max-height: 100vh;
  height: 100%;
  display: block;
  object-fit: fill;
}

.block {
  width: 100%;
  height: 100vh;
}

#block1 {
  background: black;
}

#block2 {
  background: yellow;
}

#block3 {
  background: red;
}

<div class="container-fluid header">
  <div class="header">

    <div class="video-container">
      <video autoplay muted id="video-bg">

        <source src="https://static.videezy.com/system/resources/previews/000/003/951/original/downtownla.mp4" type="video/mp4"/>

      </video>
    </div>
  </div>
</div>

<div id="block1" class="block">

</div>
<div id="block2" class="block">

</div>
<div id="block3" class="block">

</div>


问:
get parentNode STYLE
When drop any component onto other then I want to interchange the CSS styles of parentNode of component.

Example :

Before

```<code> <div class="parentDIV_1" Style="HOrizontal_interchange CSS">
      Component_1
    </div>

    <div class="parentDIV_2" Style="Vertical_interchange CSS">
       Component_2
    </div>
</code>```

Now i want to interchange the CSS of both class at run time(when drag & Drop)

After

```<code><div class="parentDIV_1" **Style="Vertical_interchange CSS"**>
      Component_1
    </div>

    <div class="parentDIV_2" **Style="HOrizontal_interchange CSS"**>
       Component_2
    </div>
</code>```

答:
I'm guessing here but it seems that you want to swap the CSS styles of two elements after some drag&drop event.

How about this solution:

Create four CSS classes:

```<code> .parentDIV_1 { ... }
 .parentDIV_2 { ... }
 .horiz { ... }
 .vert { ... }
</code>```

Assign two classes to the divs:

```<code><div class="parentDIV_1 horiz"> ...</div>

<div class="parentDIV_2 vert"> ...</div>
</code>```

Now you can toggle them:

```<code>    $('.horiz').toggleClass('vert').toggleClass('horiz');
    $('.vert').toggleClass('vert').toggleClass('horiz');
</code>```

Title: get parentNode STYLE

Body:
When drop any component onto other then I want to interchange the CSS styles of parentNode of component.

Example :

Before

      Component_1

       Component_2

Now i want to interchange the CSS of both class at run time(when drag & Drop)

After

      Component_1

       Component_2

Body:
I'm guessing here but it seems that you want to swap the CSS styles of two elements after some drag&drop event.

How about this solution:

Create four CSS classes:

 .parentDIV_1 { ... }
 .parentDIV_2 { ... }
 .horiz { ... }
 .vert { ... }

Assign two classes to the divs:

<div class="parentDIV_1 horiz"> ...</div>

<div class="parentDIV_2 vert"> ...</div>

Now you can toggle them:

    $('.horiz').toggleClass('vert').toggleClass('horiz');
    $('.vert').toggleClass('vert').toggleClass('horiz');


问:
How can I filter data from dropdown list?
I would like to filter state on my graph by dropdown list. For instance, I have density graph and dropdown of state list, when I change state graph should be changed as on state. However, with my code when I change the state, it has not something to happen.

My code :

SERVER

```<code>  output$overat <- renderPlot({
   filtered <-
   Medi_sum_small %>%
   filter(State == input$e1)
  ggplot(Medi_sum_small, aes(Hospital_Ownership)) +
    geom_density(aes(fill=factor(Hospital_overall_rating)), alpha=0.7) +
    labs(x="Ownership",
         fill="Overall rating") +
    scale_x_discrete(labels = function(x) str_wrap(x,width=0.3))

  })
</code>```

UI

```<code>box(
              title = "Select State"
              ,width = 3
              ,solidHeader = TRUE
              ,status = "primary"
              ,selectInput(
                'e1', 'State',
                c("All",unique(Medi_sum_small$State))
              )

Graphs should be changed when I change the stage.
</code>```

答:
Following up on my comment, try this -</p>

```<code>ggplot(filtered, aes(Hospital_Ownership)) +
    geom_density(aes(fill=factor(Hospital_overall_rating)), alpha=0.7) +
    labs(x="Ownership",
         fill="Overall rating") +
    scale_x_discrete(labels = function(x) str_wrap(x,width=0.3))
</code>```

Body:
I would like to filter state on my graph by dropdown list. For instance, I have density graph and dropdown of state list, when I change state graph should be changed as on state. However, with my code when I change the state, it has not something to happen.

My code :

SERVER

  output$overat <- renderPlot({
   filtered <-
   Medi_sum_small %>%
   filter(State == input$e1)
  ggplot(Medi_sum_small, aes(Hospital_Ownership)) +
    geom_density(aes(fill=factor(Hospital_overall_rating)), alpha=0.7) +
    labs(x="Ownership",
         fill="Overall rating") +
    scale_x_discrete(labels = function(x) str_wrap(x,width=0.3))

  })

UI

box(
              title = "Select State"
              ,width = 3
              ,solidHeader = TRUE
              ,status = "primary"
              ,selectInput(
                'e1', 'State',
                c("All",unique(Medi_sum_small$State))
              )

Graphs should be changed when I change the stage.

Body:
Following up on my comment, try this -

ggplot(filtered, aes(Hospital_Ownership)) +
    geom_density(aes(fill=factor(Hospital_overall_rating)), alpha=0.7) +
    labs(x="Ownership",
         fill="Overall rating") +
    scale_x_discrete(labels = function(x) str_wrap(x,width=0.3))


问:
Assist me in finding the error: invalid method declaration; return type required
This is my last homework for my java class and I have been trying to run this through a compiler but I don't understand whats wrong with the code.

I tried using void after reading about how that would fix the return type issue but that just made it worse, maybe I was putting void in the wrong place.

```<code>public class Exercise09_01 {
    private double width = 1;
    private double height = 1;

    public Rectangle() {
    }

    public Rectangle(double newWidth, double newHeight) {
        width = newWidth;
        height = newHeight;
    }

    public double getArea() {
        return width * height;
    }

    public double getPerimeter() {
        return 2 * (width + height);
    }

    public static void main(String[] args) {
        Rectangle rectangle1 = new Rectangle(4, 40);
        System.out.println("The area of a 4.0 x 40.0 Rectangle is " +
        rectangle1.getArea());
        System.out.println("The perimeter of a 4.0 x 40.0 Rectangle is " +
        rectangle1.getPerimeter());
        Rectangle rectangle2 = new Rectangle(3.5, 35.9);
        System.out.println("The area of a 3.5 x 35.9 Rectangle is " +
        rectangle2.getArea());
        System.out.println("The perimeter of a 3.5 x 35.9 Rectangle is " +
        rectangle2.getPerimeter());
    }
}
</code>```

This is my last homework for this class I just want this over with any help is appreciated.

答:
The constructor name should have the same name as the class name</p>

```<code>    public class Exercise09_01 {
        private double width = 1;
        private double height = 1;

        public Exercise09_01() {
        }

        public Exercise09_01(double newWidth, double newHeight) {
            width = newWidth;
            height = newHeight;
        }
   }
</code>```

Body:
This is my last homework for my java class and I have been trying to run this through a compiler but I don't understand whats wrong with the code.

I tried using void after reading about how that would fix the return type issue but that just made it worse, maybe I was putting void in the wrong place.

public class Exercise09_01 {
    private double width = 1;
    private double height = 1;

    public Rectangle() {
    }

    public Rectangle(double newWidth, double newHeight) {
        width = newWidth;
        height = newHeight;
    }

    public double getArea() {
        return width * height;
    }

    public double getPerimeter() {
        return 2 * (width + height);
    }

    public static void main(String[] args) {
        Rectangle rectangle1 = new Rectangle(4, 40);
        System.out.println("The area of a 4.0 x 40.0 Rectangle is " +
        rectangle1.getArea());
        System.out.println("The perimeter of a 4.0 x 40.0 Rectangle is " +
        rectangle1.getPerimeter());
        Rectangle rectangle2 = new Rectangle(3.5, 35.9);
        System.out.println("The area of a 3.5 x 35.9 Rectangle is " +
        rectangle2.getArea());
        System.out.println("The perimeter of a 3.5 x 35.9 Rectangle is " +
        rectangle2.getPerimeter());
    }
}

This is my last homework for this class I just want this over with any help is appreciated.

Body:
The constructor name should have the same name as the class name

    public class Exercise09_01 {
        private double width = 1;
        private double height = 1;

        public Exercise09_01() {
        }

        public Exercise09_01(double newWidth, double newHeight) {
            width = newWidth;
            height = newHeight;
        }
   }


问:
Display what AVSpeechSynthesizer is showing as subtitles with Swift
I have an array with quotations, and am using a button to start a random quotation playing from the array.

I'm wondering, how would I have the selected random quotation also displayed in the ViewController so that people can read what the speechsynthesizer is reading?

答:
Add a label to your view and and set the quote text to it

```<code>quoteLabel.text = randomQuote
</code>```

To show your label on multiple rows add:

```<code>label.numberOfLines = 0
</code>```

Body:
Add a label to your view and and set the quote text to it

quoteLabel.text = randomQuote

To show your label on multiple rows add:

label.numberOfLines = 0


问:
Value in register printing as a different number
So I am taking computing machinery course in university this spring and we don't get any kind of decent assistance with assignments.

I have a program that multiplies two binary values using add-shift method which works fine for small numbers of any sign, but I need it to work with 2 certain numbers for part B of the assignment.

While debugging I have discovered that the code has the right product stored in the register but after printing the number shown is not the same as the number in the register.

Sorry if I posted too much code or didn't post enough information, please let me know if I should change anything about the post.

The code is all done through putty connecting to the school's server which is run on linux.

This is where the debugger shows that register x3 (which stores the product argument for the printf formatting) holds the right number immediately before the print statement

```<code>(gdb) i r x3
x3             0x1850505038     104426655800

</code>```

This is after the print statement where it prints the wrong number

```<code>(gdb) next
50              bl      printf
(gdb) next
522133279 times 200 equals 1347440696
</code>```

Here is the program

```<code>        define(multiplicand, w19)
        define(multiplier, w20)
        define(product, w21)
        define(i, w22)
        define(temp3, w23)

        define(result, x24)
        define(temp1, x25)
        define(temp2, x26)

fmt:    .string "Multiplicand: %d \nMultiplier: %d\n"
msg:    .asciz "%d times %d equals %d\n"
        .balign 4
        .global main
main:   stp     x29, x30, [sp, -16]!
        mov     x29, sp

        mov     multiplicand, 0b11111000111110001111100011111
        mov     multiplier, 0b11001000

        adrp    x0, fmt
        add     x0, x0, :lo12:fmt
        mov     w1, multiplicand
        mov     w2, multiplier
        bl      printf

        mov     i, 0
        mov     temp3, 1
loop:
        cmp     i, 32
        b.eq    print
        tst     multiplier, temp3
        b.eq    count
        uxtw    temp1, multiplicand
        uxtw    temp2, i
        lsl     temp1, temp1, temp2
        add     result, result, temp1
count:
        add     i, i, 1
        lsl     temp3, temp3, 1
        b       loop
print:
        ldr     x0, =msg
        mov     w1, multiplicand
        mov     w2, multiplier
        mov     x3, result
        bl      printf

        mov     w0, 0
        ldp     x29, x30, [sp], 16
        ret
</code>```

There were no error messages

The expression i'm trying to compute is:

522133279 * 200 = 104 426 655 800

The value that printed was 1 347 440 696, but this value came from the register that had the correct value stored immediately before the print statement

答:
1347440696 in hex is 0x50505038

104426655800 in hex is 0x1850505038

Do you see the problem?

Make sure the formatting string (see comment) matches the data you are actually feeding to printf

Body:
So I am taking computing machinery course in university this spring and we don't get any kind of decent assistance with assignments.

I have a program that multiplies two binary values using add-shift method which works fine for small numbers of any sign, but I need it to work with 2 certain numbers for part B of the assignment.

While debugging I have discovered that the code has the right product stored in the register but after printing the number shown is not the same as the number in the register.

Sorry if I posted too much code or didn't post enough information, please let me know if I should change anything about the post.

The code is all done through putty connecting to the school's server which is run on linux.

This is where the debugger shows that register x3 (which stores the product argument for the printf formatting) holds the right number immediately before the print statement

(gdb) i r x3
x3             0x1850505038     104426655800

This is after the print statement where it prints the wrong number

(gdb) next
50              bl      printf
(gdb) next
522133279 times 200 equals 1347440696

Here is the program

        define(multiplicand, w19)
        define(multiplier, w20)
        define(product, w21)
        define(i, w22)
        define(temp3, w23)

        define(result, x24)
        define(temp1, x25)
        define(temp2, x26)

fmt:    .string "Multiplicand: %d \nMultiplier: %d\n"
msg:    .asciz "%d times %d equals %d\n"
        .balign 4
        .global main
main:   stp     x29, x30, [sp, -16]!
        mov     x29, sp

        mov     multiplicand, 0b11111000111110001111100011111
        mov     multiplier, 0b11001000

        adrp    x0, fmt
        add     x0, x0, :lo12:fmt
        mov     w1, multiplicand
        mov     w2, multiplier
        bl      printf

        mov     i, 0
        mov     temp3, 1
loop:
        cmp     i, 32
        b.eq    print
        tst     multiplier, temp3
        b.eq    count
        uxtw    temp1, multiplicand
        uxtw    temp2, i
        lsl     temp1, temp1, temp2
        add     result, result, temp1
count:
        add     i, i, 1
        lsl     temp3, temp3, 1
        b       loop
print:
        ldr     x0, =msg
        mov     w1, multiplicand
        mov     w2, multiplier
        mov     x3, result
        bl      printf

        mov     w0, 0
        ldp     x29, x30, [sp], 16
        ret

There were no error messages

The expression i'm trying to compute is:

522133279 * 200 = 104 426 655 800

The value that printed was 1 347 440 696, but this value came from the register that had the correct value stored immediately before the print statement


问:
Referencing one strategy through another
When defining strategies, is it possible to reference another strategy?

@given(maximum=strategies.floats(min_value=0),
       actual=strategies.floats(max_value=maximum))
def foo(maximum, actual):
    pass
```

<p>This throws <code>NameError: 'maximum' not defined'</code></p>

<p>Edit:</p>

<p>A workaround (or perhaps <em>the</em> workaround), is to use hypothesis's <code>assume</code> function. In my case, it looks like:</p>

<pre class="lang-py prettyprint-override"><code>@given(maximum=strategies.floats(min_value=0),
       actual=strategies.floats(min_value=0))
def foo(maximum, actual):
    assume(actual <= maximum)
    pass
</code>```

答:
Your options can be summarised as "do it by rejecting some examples" (with .filter() or assume(), or "do it by construction".

The latter is generally more efficient, though it may require more code.  If you do want to try satisfying your constraints by construction, you'll need to either write a @st.composite strategy that supplies several arguments as a tuple; or go all the way to the st.data() strategy and draw interactively inside your test.

Or... in simple cases like this one, you could just put if actual > maximum: actual, maximum = maximum, actual at the top of the test function.

Body:
When defining strategies, is it possible to reference another strategy?

@given(maximum=strategies.floats(min_value=0),
       actual=strategies.floats(max_value=maximum))
def foo(maximum, actual):
    pass

This throws NameError: 'maximum' not defined'

Edit:

A workaround (or perhaps the workaround), is to use hypothesis's assume function. In my case, it looks like:

@given(maximum=strategies.floats(min_value=0),
       actual=strategies.floats(min_value=0))
def foo(maximum, actual):
    assume(actual <= maximum)
    pass


问:
Add migration error: No database provider has been configured for this DbContext
Adding migrations and updating database were working fine but seem to have hit a snag after updating to the latest version of Entity Framework core.
What am I missing?

Failing Command

```<code>add-migration authenticationtoken -Context ApplicationDbContext -verbose
</code>```

ApplicationDbContext.cs

```<code>public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
  {
    // I added this constructor after add-migration complained about
    //needing a paramterless contructor.
    public ApplicationDbContext()
    {
    }

    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }
   ...................
}
</code>```

Startup.cs

```<code>public void ConfigureServices(IServiceCollection services)
    {
      services.AddDbContext<ApplicationDbContext>(options=>       options.UseSqlServer(Configuration.GetConnectionString("SQLServerConnectionString")));
..............
}
</code>```

Program.cs

```<code>public class Program
  {
    public static void Main(string[] args)
    {
      try
      {
        WebHost.CreateDefaultBuilder(args)
          .UseStartup<Startup>()
          .UseSerilog()
          .Build()
          .Run();
      }
      finally
      {
        Log.CloseAndFlush();
      }
    }
  }
</code>```

project.csproj:

```<code><Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netcoreapp2.2</TargetFramework>
    <LangVersion>default</LangVersion>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Braintree" Version="4.11.0" />
    <PackageReference Include="BuildBundlerMinifier" Version="2.9.406" />
    <PackageReference Include="Hangfire" Version="1.7.3" />
    <PackageReference Include="Microsoft.AspNetCore.App" />
    <PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
    <PackageReference Include="Microsoft.Azure.Cosmos.Table" Version="1.0.1" />
    <PackageReference Include="Microsoft.Azure.Storage.Blob" Version="10.0.3" />
    <PackageReference Include="Microsoft.Azure.Storage.Common" Version="10.0.3" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.2.3" />
    <PackageReference Include="morelinq" Version="3.1.1" />
    <PackageReference Include="Newtonsoft.Json" Version="12.0.2" />
    <PackageReference Include="Sendgrid" Version="9.11.0" />
    <PackageReference Include="Serilog.AspNetCore" Version="2.1.1" />
    <PackageReference Include="Serilog.Extensions.Logging" Version="2.0.4" />
    <PackageReference Include="Serilog.Settings.AppSettings" Version="2.2.2" />
    <PackageReference Include="Serilog.Settings.Configuration" Version="3.0.1" />
    <PackageReference Include="Serilog.Sinks.MSSqlServer" Version="5.1.2" />
    <PackageReference Include="Stripe.net" Version="26.0.0" />
    <PackageReference Include="Syncfusion.EJ2.AspNet.Core" Version="17.1.0.48" />
  </ItemGroup>
</Project>
</code>```

StackTrace:

```<code>System.InvalidOperationException: No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions<TContext> object in its constructor and passes it to the base constructor for DbContext.
   at Microsoft.EntityFrameworkCore.Internal.DbContextServices.Initialize(IServiceProvider scopedProvider, IDbContextOptions contextOptions, DbContext context)
   at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
   at Microsoft.EntityFrameworkCore.DbContext.Microsoft.EntityFrameworkCore.Infrastructure.IInfrastructure<System.IServiceProvider>.get_Instance()
   at Microsoft.EntityFrameworkCore.Internal.InternalAccessorExtensions.GetService[TService](IInfrastructure`1 accessor)
   at Microsoft.EntityFrameworkCore.Infrastructure.AccessorExtensions.GetService[TService](IInfrastructure`1 accessor)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func`1 factory)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)
   at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigration.<>c__DisplayClass0_1.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions<TContext> object in its constructor and passes it to the base constructor for DbContext.
</code>```

答:
Thank you @ivanStoev for your link, I was able to fix the issue by adding a public static CreateWebHostBuilder method, (which I had mistakenly refactored).

Program.cs:

```<code>public class Program
  {
    public static void Main(string[] args)
    {
      try
      {
        var iWebHost = CreateWebHostBuilder(args).Build();
        Log.Information("Application starting");
        iWebHost.Run();
      }
      catch (Exception exception)
      {
        Log.Error(exception.ToString());
      }
      finally
      {
        Log.CloseAndFlush();
      }
    }
    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .UseSerilog();
  }
</code>```

Body:
Adding migrations and updating database were working fine but seem to have hit a snag after updating to the latest version of Entity Framework core.
What am I missing?

Failing Command

add-migration authenticationtoken -Context ApplicationDbContext -verbose

ApplicationDbContext.cs

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
  {
    // I added this constructor after add-migration complained about
    //needing a paramterless contructor.
    public ApplicationDbContext()
    {
    }

    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }
   ...................
}

Startup.cs

public void ConfigureServices(IServiceCollection services)
    {
      services.AddDbContext<ApplicationDbContext>(options=>       options.UseSqlServer(Configuration.GetConnectionString("SQLServerConnectionString")));
..............
}

Program.cs

public class Program
  {
    public static void Main(string[] args)
    {
      try
      {
        WebHost.CreateDefaultBuilder(args)
          .UseStartup<Startup>()
          .UseSerilog()
          .Build()
          .Run();
      }
      finally
      {
        Log.CloseAndFlush();
      }
    }
  }

project.csproj:

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netcoreapp2.2</TargetFramework>
    <LangVersion>default</LangVersion>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Braintree" Version="4.11.0" />
    <PackageReference Include="BuildBundlerMinifier" Version="2.9.406" />
    <PackageReference Include="Hangfire" Version="1.7.3" />
    <PackageReference Include="Microsoft.AspNetCore.App" />
    <PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
    <PackageReference Include="Microsoft.Azure.Cosmos.Table" Version="1.0.1" />
    <PackageReference Include="Microsoft.Azure.Storage.Blob" Version="10.0.3" />
    <PackageReference Include="Microsoft.Azure.Storage.Common" Version="10.0.3" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.2.3" />
    <PackageReference Include="morelinq" Version="3.1.1" />
    <PackageReference Include="Newtonsoft.Json" Version="12.0.2" />
    <PackageReference Include="Sendgrid" Version="9.11.0" />
    <PackageReference Include="Serilog.AspNetCore" Version="2.1.1" />
    <PackageReference Include="Serilog.Extensions.Logging" Version="2.0.4" />
    <PackageReference Include="Serilog.Settings.AppSettings" Version="2.2.2" />
    <PackageReference Include="Serilog.Settings.Configuration" Version="3.0.1" />
    <PackageReference Include="Serilog.Sinks.MSSqlServer" Version="5.1.2" />
    <PackageReference Include="Stripe.net" Version="26.0.0" />
    <PackageReference Include="Syncfusion.EJ2.AspNet.Core" Version="17.1.0.48" />
  </ItemGroup>
</Project>

StackTrace:

System.InvalidOperationException: No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions<TContext> object in its constructor and passes it to the base constructor for DbContext.
   at Microsoft.EntityFrameworkCore.Internal.DbContextServices.Initialize(IServiceProvider scopedProvider, IDbContextOptions contextOptions, DbContext context)
   at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
   at Microsoft.EntityFrameworkCore.DbContext.Microsoft.EntityFrameworkCore.Infrastructure.IInfrastructure<System.IServiceProvider>.get_Instance()
   at Microsoft.EntityFrameworkCore.Internal.InternalAccessorExtensions.GetService[TService](IInfrastructure`1 accessor)
   at Microsoft.EntityFrameworkCore.Infrastructure.AccessorExtensions.GetService[TService](IInfrastructure`1 accessor)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func`1 factory)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)
   at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigration.<>c__DisplayClass0_1.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions<TContext> object in its constructor and passes it to the base constructor for DbContext.

Body:
Thank you @ivanStoev for your link, I was able to fix the issue by adding a public static CreateWebHostBuilder method, (which I had mistakenly refactored).

Program.cs:

public class Program
  {
    public static void Main(string[] args)
    {
      try
      {
        var iWebHost = CreateWebHostBuilder(args).Build();
        Log.Information("Application starting");
        iWebHost.Run();
      }
      catch (Exception exception)
      {
        Log.Error(exception.ToString());
      }
      finally
      {
        Log.CloseAndFlush();
      }
    }
    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .UseSerilog();
  }


问:
Unsuccessfully await to retrieve sub-collection
I've tried await/async approaches for retrieving the collection associated with my firebase doc.  The data is retrieved and debug log printed to console; however, it's after the calling function has returned.  Any help would be appreciated.  I've used the Angular firestore documentation: https://github.com/angular/angularfire2/blob/master/docs/firestore/collections.md

I'm using a subscription to the data and have tried await on the snapshot

// Client call
async doSearch() {
const col = await this.service.getLogbookEntries(this.searchDoc.id)
      .then(entries => {
        for (let i = 0; i < entries.length; i++) {
          // Do something with entry
          const entry = entries[0];
        }
      });
}

// Collection retrieval
async getLogbookEntries(docId: string): Promise<LogbookEntry[]>
  // Retrieve sub collection and convert
  return new Promise((resolve) => {
    const entries: LogbookEntry[] = [];
    console.log("Retrieving logbook entries: ", docId);
    const doc = this.db.doc(`${this.endpoint}/${docId}`);
    doc.collection<Usage>("Usage").snapshotChanges()
      .subscribe(async a => {
          for (let i = 0; i < a.length; i++) {
            let data = a[i].payload.doc.data();
            let id = a[i].payload.doc.id;
            console.log("Cleaning ID: ", id, " Data: ", data);
            entries.push(this.toLogbookEntry(id, data);
          }
          resolve(entries);
        });
    });
```

<p>The client call is returning, even though there is an await on the promise returned.</p>

<p><strong>Update</strong>
I was able to get a proper await based on the following:</p>

<pre class="lang-js prettyprint-override"><code>  async getLogbookEntries(docId: string): Promise<LogbookEntry[]> {
    const entries: LogbookEntry[] = [];
    console.log("Retrieving logbook entries: ", docId);
    const doc = this.db.doc(`${this.endpoint}/${docId}`);
    // Explicitly convert to promise.
    const cleaningCol = await doc.collection<ICleaning>("cleanings").get().toPromise();
    const cleaningsChanges = cleaningCol.docChanges();
    for (let i = 0; i < cleaningsChanges.length; i++) {
      const id = cleaningsChanges[i].doc.id;
      const data = cleaningsChanges[i].doc.data();
      console.log("Cleaning: ", data);
      entries.push(this.toLogbookEntry(id, LogbookType.Cleaning, data as ICleaning));
    }
</code>```

答:
The root cause of your problem is that you are mixing the notion of subscribing to the data in your firebase doc and retrieving the data in your firebase doc (using async/await). You will need to refactor this solution use one pattern or the other (subscribe patter or async fetching pattern).

```<code>    doSearchOnChanges() {
    const col = await this.service.getLogbookEntries(this.searchDoc.id, doStuffAfterRetrieval)
      function doStuffAfterRetrieval = entries => {
        for (let i = 0; i < entries.length; i++) {
          // Do something with entry
          const entry = entries[0];
        }
      };
     }

 // Collection retrieval
 getLogbookEntries(docId: string, doStuff: entry => void): void
  // Retrieve sub collection and convert
    const entries: LogbookEntry[] = [];
    console.log("Retrieving logbook entries: ", docId);
    const doc = this.db.doc(`${this.endpoint}/${docId}`);
    doc.collection<Usage>("Usage").snapshotChanges()
      .subscribe(async a => {
          for (let i = 0; i < a.length; i++) {
            let data = a[i].payload.doc.data();
            let id = a[i].payload.doc.id;
            console.log("Cleaning ID: ", id, " Data: ", data);
            entries.push(this.toLogbookEntry(id, data);
          }
          doStuff(entries);
        });
</code>```

This is more or less how you would refactor your code into a proper use of subscription. I'm not very familiar with the firebase api, but on a cursory google search to get data and not subscribe to it you need to use the .get() function on collections. (Also ProTip: Don't ever use .then when you are using async/await. Its redundant and will lead to bugs more often then not. Pick one pattern and stick with it.)

```<code>async doSearch() {
  const col = await this.service.getLogbookEntries(this.searchDoc.id);
  for (let i = 0; i < col.length; i++) {
    // Do something with entry
    const entry = entries[0];
  }
}

// Collection retrieval
async getLogbookEntries(docId: string): Promise<LogbookEntry[]> {
  // Retrieve sub collection and convert
  // Don't create your own promises. Async/Await and the Firbase API will do this for you
    const entries: LogbookEntry[] = [];
    console.log("Retrieving logbook entries: ", docId);
    const doc = this.db.doc(`${this.endpoint}/${docId}`);
    const returnedData = await doc.collection<Usage>("Usage").get();
    for (let i = 0; i < returnedData.length; i++) {
      let data = returnedData[i].payload.doc.data();
      let id = returnedData[i].payload.doc.id;
      console.log("Cleaning ID: ", id, " Data: ", data);
      entries.push(this.toLogbookEntry(id, data));
    }
    return entries;
}
</code>```

Body:
I've tried await/async approaches for retrieving the collection associated with my firebase doc.  The data is retrieved and debug log printed to console; however, it's after the calling function has returned.  Any help would be appreciated.  I've used the Angular firestore documentation: https://github.com/angular/angularfire2/blob/master/docs/firestore/collections.md

I'm using a subscription to the data and have tried await on the snapshot

// Client call
async doSearch() {
const col = await this.service.getLogbookEntries(this.searchDoc.id)
      .then(entries => {
        for (let i = 0; i < entries.length; i++) {
          // Do something with entry
          const entry = entries[0];
        }
      });
}

// Collection retrieval
async getLogbookEntries(docId: string): Promise<LogbookEntry[]>
  // Retrieve sub collection and convert
  return new Promise((resolve) => {
    const entries: LogbookEntry[] = [];
    console.log("Retrieving logbook entries: ", docId);
    const doc = this.db.doc(`${this.endpoint}/${docId}`);
    doc.collection<Usage>("Usage").snapshotChanges()
      .subscribe(async a => {
          for (let i = 0; i < a.length; i++) {
            let data = a[i].payload.doc.data();
            let id = a[i].payload.doc.id;
            console.log("Cleaning ID: ", id, " Data: ", data);
            entries.push(this.toLogbookEntry(id, data);
          }
          resolve(entries);
        });
    });

The client call is returning, even though there is an await on the promise returned.

Update
I was able to get a proper await based on the following:

  async getLogbookEntries(docId: string): Promise<LogbookEntry[]> {
    const entries: LogbookEntry[] = [];
    console.log("Retrieving logbook entries: ", docId);
    const doc = this.db.doc(`${this.endpoint}/${docId}`);
    // Explicitly convert to promise.
    const cleaningCol = await doc.collection<ICleaning>("cleanings").get().toPromise();
    const cleaningsChanges = cleaningCol.docChanges();
    for (let i = 0; i < cleaningsChanges.length; i++) {
      const id = cleaningsChanges[i].doc.id;
      const data = cleaningsChanges[i].doc.data();
      console.log("Cleaning: ", data);
      entries.push(this.toLogbookEntry(id, LogbookType.Cleaning, data as ICleaning));
    }

Body:
The root cause of your problem is that you are mixing the notion of subscribing to the data in your firebase doc and retrieving the data in your firebase doc (using async/await). You will need to refactor this solution use one pattern or the other (subscribe patter or async fetching pattern).

    doSearchOnChanges() {
    const col = await this.service.getLogbookEntries(this.searchDoc.id, doStuffAfterRetrieval)
      function doStuffAfterRetrieval = entries => {
        for (let i = 0; i < entries.length; i++) {
          // Do something with entry
          const entry = entries[0];
        }
      };
     }

 // Collection retrieval
 getLogbookEntries(docId: string, doStuff: entry => void): void
  // Retrieve sub collection and convert
    const entries: LogbookEntry[] = [];
    console.log("Retrieving logbook entries: ", docId);
    const doc = this.db.doc(`${this.endpoint}/${docId}`);
    doc.collection<Usage>("Usage").snapshotChanges()
      .subscribe(async a => {
          for (let i = 0; i < a.length; i++) {
            let data = a[i].payload.doc.data();
            let id = a[i].payload.doc.id;
            console.log("Cleaning ID: ", id, " Data: ", data);
            entries.push(this.toLogbookEntry(id, data);
          }
          doStuff(entries);
        });

This is more or less how you would refactor your code into a proper use of subscription. I'm not very familiar with the firebase api, but on a cursory google search to get data and not subscribe to it you need to use the .get() function on collections. (Also ProTip: Don't ever use .then when you are using async/await. Its redundant and will lead to bugs more often then not. Pick one pattern and stick with it.)

async doSearch() {
  const col = await this.service.getLogbookEntries(this.searchDoc.id);
  for (let i = 0; i < col.length; i++) {
    // Do something with entry
    const entry = entries[0];
  }
}

// Collection retrieval
async getLogbookEntries(docId: string): Promise<LogbookEntry[]> {
  // Retrieve sub collection and convert
  // Don't create your own promises. Async/Await and the Firbase API will do this for you
    const entries: LogbookEntry[] = [];
    console.log("Retrieving logbook entries: ", docId);
    const doc = this.db.doc(`${this.endpoint}/${docId}`);
    const returnedData = await doc.collection<Usage>("Usage").get();
    for (let i = 0; i < returnedData.length; i++) {
      let data = returnedData[i].payload.doc.data();
      let id = returnedData[i].payload.doc.id;
      console.log("Cleaning ID: ", id, " Data: ", data);
      entries.push(this.toLogbookEntry(id, data));
    }
    return entries;
}


问:
Running e-commerce site from a web service. Bad idea?
The company I work for makes a complex accounting application. This is a desktop app that connects to a local database server on the client's network. Some of our clients want to get e-commerce sites built but they will need access to this data.

Is it OK to install the web site at one location and feed data to it from a web server in another location. I've built stuff like this in the past and I know it could potential be slow. I'm hoping to mitigate this problem with stacks of Asp.NET caching. Is this a reasonable architecture (for a small to medium size e-commerce site) or will it run like a dog? Due to much pain in the past, I'm trying to keep this simple and avoid any sort of replication of the database.

Cheers

Ma

答:
Well, replication of the database might actually be the fastest option. Think about it: getting a whole bunch of data on each request, with some cache misses, or basically having a 'complete' local cache (and thus no cache misses, well, not in-transfer anyway, your DB might cache, of course).

Edit: so basically my answer would be: no, it's not OK to run the website and database in two completely different locations. Two boxes in the same rack could be OK, but it seems that it would be preferable to have your web-service and DB on the same (virtual) machine.


问:
How do I perform either a push UIViewController or a present of UIAlertController?
After some API calls, I have a check to either navigate to another screen or show an alert on the same screen. Currently, I am doing this by creating an observable that returns a UIViewController type but pushing a UIAlertController causes problem.

Any suggestions/ideas on how this should be done?

ViewModel.swift

```<code>let nextAction = Observable.combineLatest(appVersionOutput, serviceAvailabilityOutput, getLanguagePackOutput,
                                              resultSelector:
        { appVersion, _, _ -> UIViewController in
            if appVersion.currentAppVersion == "1.0.0" {
                let appServiceAvailability = Availability.shared.getAppStatus()
                if appServiceAvailability {
                    return LoginLandingViewController()
                } else {
                    return ServiceMaintenanceViewController()
                }
            } else {
                return UIAlertController()
            }
        })
</code>```

ViewController.swift

```<code>viewModel.output.nextAction
        .subscribe(onNext: { [weak self] screen in
            self?.navigationController?.pushViewController(screen, animated: true)
        }) // PROBLEM FACED: Pushing a UIAlertController
        .disposed(by: disposeBag)
</code>```

答:
You can check the class using classForCoder

```<code>viewModel.output.nextAction
    .subscribe(onNext: { [weak self] screen in
        if String(describing: screen.classForCoder) == "UIAlertController" {
            //present
            self?.present(screen, animated: true, completion: nil)
        } else {
            //navigate
            self?.navigationController?.pushViewController(screen, animated: true)
        }
    }) // PROBLEM FACED: Pushing a UIAlertController
    .disposed(by: disposeBag)
</code>```

Body:
After some API calls, I have a check to either navigate to another screen or show an alert on the same screen. Currently, I am doing this by creating an observable that returns a UIViewController type but pushing a UIAlertController causes problem.

Any suggestions/ideas on how this should be done?

ViewModel.swift

let nextAction = Observable.combineLatest(appVersionOutput, serviceAvailabilityOutput, getLanguagePackOutput,
                                              resultSelector:
        { appVersion, _, _ -> UIViewController in
            if appVersion.currentAppVersion == "1.0.0" {
                let appServiceAvailability = Availability.shared.getAppStatus()
                if appServiceAvailability {
                    return LoginLandingViewController()
                } else {
                    return ServiceMaintenanceViewController()
                }
            } else {
                return UIAlertController()
            }
        })

ViewController.swift

viewModel.output.nextAction
        .subscribe(onNext: { [weak self] screen in
            self?.navigationController?.pushViewController(screen, animated: true)
        }) // PROBLEM FACED: Pushing a UIAlertController
        .disposed(by: disposeBag)

Body:
You can check the class using classForCoder

viewModel.output.nextAction
    .subscribe(onNext: { [weak self] screen in
        if String(describing: screen.classForCoder) == "UIAlertController" {
            //present
            self?.present(screen, animated: true, completion: nil)
        } else {
            //navigate
            self?.navigationController?.pushViewController(screen, animated: true)
        }
    }) // PROBLEM FACED: Pushing a UIAlertController
    .disposed(by: disposeBag)


问:
Change the Value of an existing Laravel Collection key
I have a Laravel Collection $page in which I am trying to update some values based on a value in another collection. But instead up updating a new element is being added to $page.

```<code>    if($page->get('Lang') !== null ){
        $l = $page->get('Lang');

        foreach ($l as $thisLang => $value) {
            if($lang == $thisLang){
               //  this is where I am attempt is overwrite the variable
                $page->Name = $value->Name;

                break;
            }
        }
    }
</code>```

Being fairly new to Laravel I am not sure what I am doing wrong. Any code corrections are appreciated.

I have also tried :

```<code> $page->update( ["Name" , $value->Name] );
</code>```

but get the error

```<code> "Method Illuminate\Support\Collection::update does not exist."
</code>```

答:
Instead of use $page->Name need use $page['Name'].

Corrected code is

```<code>if($page->get('Lang') !== null ){
    $l = $page->get('Lang');

    foreach ($l as $thisLang => $value) {
        if($lang == $thisLang){
           //  this is where I am attempt is overwrite the variable
            $page['Name'] = $value->Name;

            break;
        }
    }
}
</code>```

Body:
I have a Laravel Collection $page in which I am trying to update some values based on a value in another collection. But instead up updating a new element is being added to $page.

    if($page->get('Lang') !== null ){
        $l = $page->get('Lang');

        foreach ($l as $thisLang => $value) {
            if($lang == $thisLang){
               //  this is where I am attempt is overwrite the variable
                $page->Name = $value->Name;

                break;
            }
        }
    }

Being fairly new to Laravel I am not sure what I am doing wrong. Any code corrections are appreciated.

I have also tried :

 $page->update( ["Name" , $value->Name] );

but get the error

 "Method Illuminate\Support\Collection::update does not exist."

Body:
Instead of use $page->Name need use $page['Name'].

Corrected code is

if($page->get('Lang') !== null ){
    $l = $page->get('Lang');

    foreach ($l as $thisLang => $value) {
        if($lang == $thisLang){
           //  this is where I am attempt is overwrite the variable
            $page['Name'] = $value->Name;

            break;
        }
    }
}


问:
I'm getting an http header (access denied) error even though I have set up my httpheaders
I have a list of users called from a database using a spring boot API.

Each of these users has various attributes like username, id, first name, last name, registration date and profile photo which the id of an uploaded file(hosted in a sub-folder in the spring project main folder after the upload) in another database table called files.

To get an image you must a correct JWT token(which you get after signing in) and use the path: 'http://localhost:8082/downloadFile/' + imageid.

Under the users list mentioned above I've created a div which would be filled after clicking on one of the users with the selected user's attributes and show the actual user profile picture.

I found a stackoverflow post on how i could convert the image link to an actual photo so I followed the instructions.

The problem is after doing what was written in the answers I keep getting this error:

```<code>ERROR Error:
"Uncaught (in promise): HttpErrorResponse: {
    "headers": {
        "normalizedNames:{},
        "lazyUpdate":null
     },
     "status":403,
     "statusText":"OK",
     "url":"http://localhost:8082/downloadFile/e508e9c1-75e4-4cf4-86a8-fc617e4cc292",
     "ok":false,
     "name":"HttpErrorResponse",
     "message":"Http failure response for http://localhost:8082/downloadFile/e508e9c1-75e4-4cf4-86a8-fc617e4cc292: 403 OK",
    "error":{}
}"
</code>```

Here's my .ts component:

```<code>import { Component, OnInit } from '@angular/core';
import { ViewEncapsulation } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { UserService } from '../user.service';
import { MatDialog, MatDialogConfig, MatTableDataSource } from '@angular/material';
import { NewDialogComponent } from '../new-dialog/new-dialog.component';
import { DomSanitizer } from '@angular/platform-browser';
import { map } from 'rxjs-compat/operator/map';
import { Observable, Observer } from 'rxjs';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['../app.component.scss', './dashboard.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class DashboardComponent implements OnInit {
  loginuser: any = {};
  imgSrc: any = {};
  users: any[] = [];
  public dataSource = new MatTableDataSource<User>();
  displayedColumns = ['id', 'username', 'email', 'firstname', 'lastname', 'registeredDate', 'enabled'];
  constructor(private service: UserService, private http: HttpClient, private sanitizer: DomSanitizer) {
  this.loginuser = JSON.parse(localStorage.getItem('currentUser'));
  this.service.getAllUsers(this.loginuser.token).subscribe(u => {
  this.dataSource.data = u as User[];
  console.log('datasource: ', this.dataSource.filteredData);
  this.users = u;
  console.log('user: ', this.users);
  });
 }

ngOnInit() {
}

onRowClicked(selectedItem) {
  console.log('selected item: ', selectedItem);
  document.getElementById('msg').style.display = 'none';
  document.getElementById('info').style.display = 'block';
  if (selectedItem.photoProfile === 'http://localhost:8082/static.images/user/default.jpg') {
  this.imgSrc = 'C:/Users/Adam/Documents/CODE/Ang/StarAdmin-Free-Angular-Admin-Template/src/assets/default.jpg';
} else if (selectedItem.photoProfile === 'null') {
  console.log('null');
} else {
  const currentUser = JSON.parse(localStorage.getItem('currentUser'));
  console.log(currentUser.token);
  this.getFile('http://localhost:8082/downloadFile/' + selectedItem.photoProfile, currentUser.token);
}
}

getFile(url: string, token): any {
const headers = new HttpHeaders({'Authorization': 'Bearer ' + token});
this.http.get(url, {
  responseType: 'blob',
})
  .toPromise()
  .then((res: any) => {
    let blob = new Blob([res._body], {
      type: res.headers.get('Content-Type', headers)
    });

    let urlCreator = window.URL;
    this.imgSrc = this.sanitizer.bypassSecurityTrustUrl(
        urlCreator.createObjectURL(blob));
  });
}
}

export interface User {
id: number;
username: string;
firstName: string;
lastName: string;
email: string;
enabled: string;
registeredDate: Date;
}
</code>```

答:
it looks like you never pass in the headers object that you create right above the call to your GET request.  Change your request to something like:

const headers = new HttpHeaders({'Authorization': 'Bearer ' + token});

this.http.get(url, headers=headers, {
  responseType: 'blob',
})

Body:
I have a list of users called from a database using a spring boot API.

Each of these users has various attributes like username, id, first name, last name, registration date and profile photo which the id of an uploaded file(hosted in a sub-folder in the spring project main folder after the upload) in another database table called files.

To get an image you must a correct JWT token(which you get after signing in) and use the path: 'http://localhost:8082/downloadFile/' + imageid.

Under the users list mentioned above I've created a div which would be filled after clicking on one of the users with the selected user's attributes and show the actual user profile picture.

I found a stackoverflow post on how i could convert the image link to an actual photo so I followed the instructions.

The problem is after doing what was written in the answers I keep getting this error:

ERROR Error:
"Uncaught (in promise): HttpErrorResponse: {
    "headers": {
        "normalizedNames:{},
        "lazyUpdate":null
     },
     "status":403,
     "statusText":"OK",
     "url":"http://localhost:8082/downloadFile/e508e9c1-75e4-4cf4-86a8-fc617e4cc292",
     "ok":false,
     "name":"HttpErrorResponse",
     "message":"Http failure response for http://localhost:8082/downloadFile/e508e9c1-75e4-4cf4-86a8-fc617e4cc292: 403 OK",
    "error":{}
}"

Here's my .ts component:

import { Component, OnInit } from '@angular/core';
import { ViewEncapsulation } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { UserService } from '../user.service';
import { MatDialog, MatDialogConfig, MatTableDataSource } from '@angular/material';
import { NewDialogComponent } from '../new-dialog/new-dialog.component';
import { DomSanitizer } from '@angular/platform-browser';
import { map } from 'rxjs-compat/operator/map';
import { Observable, Observer } from 'rxjs';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['../app.component.scss', './dashboard.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class DashboardComponent implements OnInit {
  loginuser: any = {};
  imgSrc: any = {};
  users: any[] = [];
  public dataSource = new MatTableDataSource<User>();
  displayedColumns = ['id', 'username', 'email', 'firstname', 'lastname', 'registeredDate', 'enabled'];
  constructor(private service: UserService, private http: HttpClient, private sanitizer: DomSanitizer) {
  this.loginuser = JSON.parse(localStorage.getItem('currentUser'));
  this.service.getAllUsers(this.loginuser.token).subscribe(u => {
  this.dataSource.data = u as User[];
  console.log('datasource: ', this.dataSource.filteredData);
  this.users = u;
  console.log('user: ', this.users);
  });
 }

ngOnInit() {
}

onRowClicked(selectedItem) {
  console.log('selected item: ', selectedItem);
  document.getElementById('msg').style.display = 'none';
  document.getElementById('info').style.display = 'block';
  if (selectedItem.photoProfile === 'http://localhost:8082/static.images/user/default.jpg') {
  this.imgSrc = 'C:/Users/Adam/Documents/CODE/Ang/StarAdmin-Free-Angular-Admin-Template/src/assets/default.jpg';
} else if (selectedItem.photoProfile === 'null') {
  console.log('null');
} else {
  const currentUser = JSON.parse(localStorage.getItem('currentUser'));
  console.log(currentUser.token);
  this.getFile('http://localhost:8082/downloadFile/' + selectedItem.photoProfile, currentUser.token);
}
}

getFile(url: string, token): any {
const headers = new HttpHeaders({'Authorization': 'Bearer ' + token});
this.http.get(url, {
  responseType: 'blob',
})
  .toPromise()
  .then((res: any) => {
    let blob = new Blob([res._body], {
      type: res.headers.get('Content-Type', headers)
    });

    let urlCreator = window.URL;
    this.imgSrc = this.sanitizer.bypassSecurityTrustUrl(
        urlCreator.createObjectURL(blob));
  });
}
}

export interface User {
id: number;
username: string;
firstName: string;
lastName: string;
email: string;
enabled: string;
registeredDate: Date;
}


问:
Web service to find nearby points of interest?
I'm looking for a paid or free service that can return geographic points of interest within a given proximity (e.g. 10km) filtered by category, such as "Restaurants".

Factual looks promising, but doesn't support my country - South Africa. The Google Places API is still in developer preview.

There must be a mature online service that can act as an "online GPS" for finding nearby places?

答:
GeoNames API returns geolocated Wikipedia articles located near given point:

http://www.geonames.org/export/wikipedia-webservice.html

SimpleGeo API returns info about given point

https://simplegeo.com/docs/api-endpoints/simplegeo-context

Here is a long list of mapping related APIs on Programmable Web. I'm sure it will give you more clues in regards to datasources:

http://www.programmableweb.com/apis/directory/1?apicat=Mapping

ContentLicense: CC BY-SA 2.5


问:
3rd party sync method freezing the UI in .NET 4.7.2 WPF
I have a .NET 4.7.2 application using WPF MVVM. I am connecting to a robot using the provided library from the manufacturer. Unfortunately, their method that connects to the robot stops for 30 seconds when the IP parameter is faulty and this essentially freezes the UI.

I decided to use async/await to fix this issue, based on this I figured it is an I/O-Bound problem, but since the method I use to connect to the robot is sync, I couldn't await it. In the examples I saw they usually used async libraries at the first place and I couldn't find how to solve this problem, when a sync method is provided by 3rd party is freezing my UI.

The first code snippet didn't work, my UI stopped for 30 seconds when I tried to connect.

public async Task<bool> ConnectToRobot(string ip = "")
        {
            if (FanucController.IsConnected)
                return true;

            var result = await ConnectToFanuc(ip);

            return result;
        }

private Task<bool> ConnectToFanuc(string ip)
        {
            try
            {
                ((IRobot)FanucController).Connect(ip);
                // Other code for connection

                return Task.FromResult(true);
            }
            catch
            {
                return Task.FromResult(false);
            }
        }
```

<p>Eventually I got around it by using the CPU-Bound example (second code snippet), however, this is not really a CPU bound problem, hence I'm not sure if this would cause problems in the future.</p>

<pre class="lang-cs prettyprint-override"><code>public async Task<bool> ConnectToRobot(string ip = "")
        {
            if (FanucController.IsConnected)
                return true;

            var result = await Task.Run(() => ConnectToFanuc(ip));

            return result;
        }

private bool ConnectToFanuc(string ip)
        {
            try
            {
                ((IRobot)FanucController).Connect(ip);
                // Other code for connection

                return true;
            }
            catch
            {
                return false;
            }
        }
</code>```

Is there a better way to solve this problem? Should I use something other than the async/await keywords?

答:
I think you have completely misunderstood what .net async is doing.

Task<T> is an implementation of the Promise monad.

This can be in a variety of states (very simply).

Not Complete

Complete with Result

Complete with Error

This is how the async/await engine does its magic. Methods can "complete" without a result.

Task.FromResult creates a Promise in the 2nd state. That means the the async/await engine has no chance to go off and do something else whilst waiting for the result.

One problem with the .net async await framework is the "Turtles/Async all the way down" problem. For async await to work properly, you need everything going down to be using the new fangled async/Task implementation (which is a pain since in general, that means reimplementing the entire library again).

A quick work-around for this is to use Task.Run. It is an acceptable workaround, for 3rd party libraries which do not support async/await.

Body:
I have a .NET 4.7.2 application using WPF MVVM. I am connecting to a robot using the provided library from the manufacturer. Unfortunately, their method that connects to the robot stops for 30 seconds when the IP parameter is faulty and this essentially freezes the UI.

I decided to use async/await to fix this issue, based on this I figured it is an I/O-Bound problem, but since the method I use to connect to the robot is sync, I couldn't await it. In the examples I saw they usually used async libraries at the first place and I couldn't find how to solve this problem, when a sync method is provided by 3rd party is freezing my UI.

The first code snippet didn't work, my UI stopped for 30 seconds when I tried to connect.

public async Task<bool> ConnectToRobot(string ip = "")
        {
            if (FanucController.IsConnected)
                return true;

            var result = await ConnectToFanuc(ip);

            return result;
        }

private Task<bool> ConnectToFanuc(string ip)
        {
            try
            {
                ((IRobot)FanucController).Connect(ip);
                // Other code for connection

                return Task.FromResult(true);
            }
            catch
            {
                return Task.FromResult(false);
            }
        }

Eventually I got around it by using the CPU-Bound example (second code snippet), however, this is not really a CPU bound problem, hence I'm not sure if this would cause problems in the future.

public async Task<bool> ConnectToRobot(string ip = "")
        {
            if (FanucController.IsConnected)
                return true;

            var result = await Task.Run(() => ConnectToFanuc(ip));

            return result;
        }

private bool ConnectToFanuc(string ip)
        {
            try
            {
                ((IRobot)FanucController).Connect(ip);
                // Other code for connection

                return true;
            }
            catch
            {
                return false;
            }
        }

Is there a better way to solve this problem? Should I use something other than the async/await keywords?


问:
How to send Notification in iOS when using firebase cloud functions?
I have been looking around many different places for how to implement notification sending using cloud functions. And the best I have found is the following: Push notifications using Firebase Cloud Function iOS

But I believe it would benefit many people as well as me, if this fragmentation were fixed with one set of instructions from start to finish.

Thus I ask: How can I implement notification sending when a user creates something at a certain spot in firebase realtime DB?

From start to finish, a very clear explanation for someone doing this for the FIRST TIME.

答: I believe this does the trick: https://github.com/onmyway133/blog/issues/64</p>


问:
fatal error C1083: Cannot open include file: 'boost/config.hpp': No such file or directory
I think I did all the necessary configuration but I am still getting this:

```<code>Error 1 fatal error C1083: Cannot open include file: 'boost/config.hpp': No such file or directory    File:c:\documents and settings\administrator\my documents\visual studio 2008\libs\boost_1_43_0\boost\smart_ptr\shared_ptr.hpp Line:17
</code>```

Here are screenshots of setting I have done to add directories for include and lib files :

Am I missing something ?

答:
Please note that you need to add the path of "boost" directory in both 64bit and 32bit configurations. While adding the path, make sure to select appropriate platform (64bit or 32bit) depending upon your need. If you compile in both versions, you need add both.

Boost library directory is valid for both the above configurations.

Body:
I think I did all the necessary configuration but I am still getting this:

Error 1 fatal error C1083: Cannot open include file: 'boost/config.hpp': No such file or directory    File:c:\documents and settings\administrator\my documents\visual studio 2008\libs\boost_1_43_0\boost\smart_ptr\shared_ptr.hpp Line:17

Here are screenshots of setting I have done to add directories for include and lib files :

Am I missing something ?


问:
My if statement conditions are not triggering properly despite the conditions being met
I'm learning how to program with Python by taking up small projects to get myself familiarized. I'm stuck on a tiny problem in which my if statement is not being triggered properly despite the conditions being met during the programs execution. this is the dice simulation project I made on my own.

I could not think of any additional methods at this time since I'm still a novice but learning as i'm going

```<code>import random
import time

print("Welcome to the dice simulator, lets find out how lucky you are!")

"\n"

min = 1
max = 6

roll = input("Do you want to play? ")

while roll == "yes" or roll == "y" or roll == "Yes" or roll == "Y":

    print("Now rolling both dice....")
    time.sleep(1)
    print("calculating....")
    time.sleep(3)

    print(random.randint(min, max))
    print(random.randint(min, max))

    if min == max: #This if condition does not work even if the dice match. Needs work.
        print("Amazing! You scored a double!")
    else: #This else condition works regardless of the outcome.
        print("Oof! Might wanna keep trying!")

    roll_again = input("Roll again? y/n: ")
    if roll_again == "n" or roll_again == "no" or roll_again == "No" or roll_again == "N":
        print("Goodbye!")
        break
    # else:
    #     print("Invalid answer")
    #     break
</code>```

If the if condition is met, a message will print congratulating the user for scoring a double number such as 1,1 or 6,6 for example. If the dice does not show matching number's, the else condition will print a message telling the user to better luck next time.

答:
That's because you preset min and max which will never be changed. Therefore, if min == max cannot be True.

You can simply keep the results in new variables:

```<code>dice_1 = random.randrange(1, 7)
dice_2 = random.randrange(1, 7)
</code>```

Then compare dice_1 and dice_2 for your conditions

Body:
I'm learning how to program with Python by taking up small projects to get myself familiarized. I'm stuck on a tiny problem in which my if statement is not being triggered properly despite the conditions being met during the programs execution. this is the dice simulation project I made on my own.

I could not think of any additional methods at this time since I'm still a novice but learning as i'm going

import random
import time

print("Welcome to the dice simulator, lets find out how lucky you are!")

"\n"

min = 1
max = 6

roll = input("Do you want to play? ")

while roll == "yes" or roll == "y" or roll == "Yes" or roll == "Y":

    print("Now rolling both dice....")
    time.sleep(1)
    print("calculating....")
    time.sleep(3)

    print(random.randint(min, max))
    print(random.randint(min, max))

    if min == max: #This if condition does not work even if the dice match. Needs work.
        print("Amazing! You scored a double!")
    else: #This else condition works regardless of the outcome.
        print("Oof! Might wanna keep trying!")

    roll_again = input("Roll again? y/n: ")
    if roll_again == "n" or roll_again == "no" or roll_again == "No" or roll_again == "N":
        print("Goodbye!")
        break
    # else:
    #     print("Invalid answer")
    #     break

If the if condition is met, a message will print congratulating the user for scoring a double number such as 1,1 or 6,6 for example. If the dice does not show matching number's, the else condition will print a message telling the user to better luck next time.

Body:
That's because you preset min and max which will never be changed. Therefore, if min == max cannot be True.

You can simply keep the results in new variables:

dice_1 = random.randrange(1, 7)
dice_2 = random.randrange(1, 7)

Then compare dice_1 and dice_2 for your conditions


问:
Material design components button global theme overriding broken
I want to simply apply styling to all buttons on a theme level like this

```<code><style name="BaseTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
     ...
    <item name="buttonStyle">@style/DefaultButton</item>
</style>

<style name="DefaultButton" parent="Widget.MaterialComponents.Button">
    <item name="android:textColor">@color/whatever</item>
</style>

<Button
    android:id="@+id/addChannelButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|center_horizontal"
    android:layout_margin="16dp"
    android:text="Add room" />
</code>```

Why doesnt this work? It would in appcompat

// If I use Theme.MaterialComponents.Light.NoActionBar.Bridge, then it works

答:
Can you try with v1.0.0-alpha06? There has been some progress since v1.0.0 which may have addressed what you're seeing.

1.1.0-alpha02

Shape Theming: FloatingActionButton, MaterialButton, Chip, MaterialCardView, BottomSheet, & TextInputLayout updated to use the new Material shape system

1.1.0-alpha06

Implement Shapeable interface in MaterialButton

Source: https://github.com/material-components/material-components-android/releases

Body:
I want to simply apply styling to all buttons on a theme level like this

<Button
    android:id="@+id/addChannelButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|center_horizontal"
    android:layout_margin="16dp"
    android:text="Add room" />

Why doesnt this work? It would in appcompat

// If I use Theme.MaterialComponents.Light.NoActionBar.Bridge, then it works


问:
crossdomain.xml not honored by jwplayer
I have a video player on this site
http://aiskacang.com/crawl/pseudo.html

The player loads a flv video file seeon.flv from another domain.
Currently, even without a crossdomain.xml in the server where seeon.flv is located, the video is loaded fine.
This is not the behavior I want or expect it to be.

I also tried putting a crossdomain.xml with the following content:

```<code><?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM
"http://www.adobe.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
<site-control permitted-cross-domain-policies="none"/>
</cross-domain-policy>
</code>```

From firebug, I could see that there's a request to the crossdomain.xml before accessing the video file (seeon.flv).
It returns the content fine , with the Content-type of application/xml, but it still allow the cross domain behavior.

Any idea ?

答:
It sounds like you may be confusing the use of crossdomain policies. Disallowing crossdomain access doesn't prevent content from being loaded and displayed. It just limits access between content from different domains after the target has been loaded and displayed. For example, if A.swf loads B.swf, A will be unable to call methods inside B. But B will still get loaded.

It sounds like what you want is hotlinking protection, which is normally done at the webserver level. (That is, you make a rule in Apache/IIS/etc. on the FLV's server to prevent it from being served to other domain's pages.)

Title: crossdomain.xml not honored by jwplayer

Body:
I have a video player on this site
http://aiskacang.com/crawl/pseudo.html

The player loads a flv video file seeon.flv from another domain.
Currently, even without a crossdomain.xml in the server where seeon.flv is located, the video is loaded fine.
This is not the behavior I want or expect it to be.

I also tried putting a crossdomain.xml with the following content:

<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM
"http://www.adobe.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
<site-control permitted-cross-domain-policies="none"/>
</cross-domain-policy>

From firebug, I could see that there's a request to the crossdomain.xml before accessing the video file (seeon.flv).
It returns the content fine , with the Content-type of application/xml, but it still allow the cross domain behavior.

Any idea ?