问:
Why does URLFOR() function for a list view button function differently between sandboxes?
I am using the URLFOR() function in a list view button to re-direct to a lightning component that implements the lightning:isUrlAddressable interface. As part of the URLFOR() function, I am passing in some  URL parameters in the third argument, one being a merge field and the other a static string  value:

{!URLFOR("lightning/cmp/c__MyComponent", null, [id=Related_Object__c.Id,sObjectName="My_SObject_Name__c"])}

This is working correctly in our DEV sandbox (API version 45.0) but the same configuration does not work in our QA sandbox (API version 46.0).

When clicking the list view button in our QA sandbox, I notice that the URL parameters are not being populated at all for "id" and "sObjectName". I confirmed this by logging the value of the PageReference variable in the Lightning component as well.

Are there any differences between the API versions or other issues that might cause this behavior?

答:
Per the Summer '19 Release Notes:

```<code>Add a Namespace Prefix to Query Parameters and pageReference.state Properties was a critical update in Winter ’19 and is enforced for the Summer ’19 release. This critical update resolves naming conflicts for query parameters between package components.
</code>```

In this way, the above query parameters need to at a minimum use the default namespace "c__":

```<code>{!URLFOR("lightning/cmp/c__MyComponent", null, [c__id=Related_Object__c.Id,c__sObjectName="My_SObject_Name__c"])}
</code>```

Documentation:
https://releasenotes.docs.salesforce.com/en-us/winter19/release-notes/rn_forcecom_general_namespace_prefix_cruc.htm

Body:
Per the Summer '19 Release Notes:

Add a Namespace Prefix to Query Parameters and pageReference.state Properties was a critical update in Winter ’19 and is enforced for the Summer ’19 release. This critical update resolves naming conflicts for query parameters between package components.

In this way, the above query parameters need to at a minimum use the default namespace "c__":

{!URLFOR("lightning/cmp/c__MyComponent", null, [c__id=Related_Object__c.Id,c__sObjectName="My_SObject_Name__c"])}

Documentation:
https://releasenotes.docs.salesforce.com/en-us/winter19/release-notes/rn_forcecom_general_namespace_prefix_cruc.htm


来源: stackexchange

问:
Error: derefferencing out of bounds pointer
Given the below code, I get the following error at runtime

FATAL RUN-TIME ERROR: line 21, col 11, thread id 0x00002068:

  Dereference of out-of-bounds pointer: 1 bytes (1 elements) past end of
  array.

What am I doing wrong here? I create a 2D char array and initialize all elements to 'x'. Then I attempt to print all elements by using the pointer logic. It prints the characters to standard IO but then throws the runtime error. I don't see where the out of bounds is occurring.

```<code>#include <stdio.h>
#define EDGE 10

int main(void){

    char fabric[EDGE][EDGE];
    char *cell = fabric;
    int totalCells = EDGE*EDGE;

    for(int i = 0; i < totalCells; ++i){
            *(cell + i) = 'x';
    }

    cell = fabric; //set cell to point back to first element

    while(*cell){                  //while there is content at address, print content
        printf("%c", *cell);
        ++cell;
    }

    getchar();
    return 0;

}
</code>```

答:
Highly recommend you just malloc/memset your structure instead of doing the hacky pointer thing.

```<code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define EDGE        ( 10 )
#define TOTAL_CELLS ( EDGE * EDGE )

int main()
{
    int i;
    char * fabric = malloc(TOTAL_CELLS);
    memset(fabric,'x',TOTAL_CELLS);

    for(i=0; i<TOTAL_CELLS; i++){
        printf("%c",fabric[i]);
    }

    return 0;
}
</code>```

If you still want to reference the 2D array-like structure (fabric[i][j]), you can do it in a 1D array just as easily (fabric[i*EDGE+j]), and its easier to manipulate that linear memory block.

ContentLicense: CC BY-SA 4.0

Body:
Given the below code, I get the following error at runtime

FATAL RUN-TIME ERROR: line 21, col 11, thread id 0x00002068:

  Dereference of out-of-bounds pointer: 1 bytes (1 elements) past end of
  array.

What am I doing wrong here? I create a 2D char array and initialize all elements to 'x'. Then I attempt to print all elements by using the pointer logic. It prints the characters to standard IO but then throws the runtime error. I don't see where the out of bounds is occurring.

#include <stdio.h>
#define EDGE 10

int main(void){

    char fabric[EDGE][EDGE];
    char *cell = fabric;
    int totalCells = EDGE*EDGE;

    for(int i = 0; i < totalCells; ++i){
            *(cell + i) = 'x';
    }

    cell = fabric; //set cell to point back to first element

    while(*cell){                  //while there is content at address, print content
        printf("%c", *cell);
        ++cell;
    }

    getchar();
    return 0;

}

Body:
Highly recommend you just malloc/memset your structure instead of doing the hacky pointer thing.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define EDGE        ( 10 )
#define TOTAL_CELLS ( EDGE * EDGE )

int main()
{
    int i;
    char * fabric = malloc(TOTAL_CELLS);
    memset(fabric,'x',TOTAL_CELLS);

    for(i=0; i<TOTAL_CELLS; i++){
        printf("%c",fabric[i]);
    }

    return 0;
}

If you still want to reference the 2D array-like structure (fabric[i][j]), you can do it in a 1D array just as easily (fabric[i*EDGE+j]), and its easier to manipulate that linear memory block.


问:
Switch statement default always showing default
I have a switch statement. It almost works fine, however instead of just showing one case, it shows the selected case then the default. Here is my code:

var people = {
  names: ["Sam", "Tim", "Steve"],
  emails: ["sam@email.com", "timm@messages.org", "stevieG@youhavemail.com"],
  phonenums: [1111, 2222, 4545]
}

var search = prompt("Type in someone's name to find their phone number and email.");

switch (search) {
  case people.names[0]:
    alert(people.names[0] + "'s email: " + people.emails[0] + " phone number: " + people.phonenums[0]);
  case people.names[1]:
    alert(people.names[1] + "'s email: " + people.emails[1] + " phone number: " + people.phonenums[1]);
  case people.names[2]:
    alert(people.names[2] + "'s email: " + people.emails[2] + " phone number: " + people.phonenums[2]);
  default:
    alert("I don't know that person.");
}```

Why does this happen?

答:
Because you don't have any break in your switch cases.

Check the documentation for the switch statement on MDN. It says the following about break (emphasis mine)

The optional break statement associated with each case label ensures that the program breaks out of switch once the matched statement is executed and continues execution at the statement following switch. If break is omitted, the program continues execution at the next statement in the switch statement.

So update your cases to look like

```<code>case people.names[0]:
  alert(people.names[0] + "'s email: " + people.emails[0] + " phone number: " + people.phonenums[0]);
  break;
</code>```

Body:
I have a switch statement. It almost works fine, however instead of just showing one case, it shows the selected case then the default. Here is my code:

var people = {
  names: ["Sam", "Tim", "Steve"],
  emails: ["sam@email.com", "timm@messages.org", "stevieG@youhavemail.com"],
  phonenums: [1111, 2222, 4545]
}

var search = prompt("Type in someone's name to find their phone number and email.");

switch (search) {
  case people.names[0]:
    alert(people.names[0] + "'s email: " + people.emails[0] + " phone number: " + people.phonenums[0]);
  case people.names[1]:
    alert(people.names[1] + "'s email: " + people.emails[1] + " phone number: " + people.phonenums[1]);
  case people.names[2]:
    alert(people.names[2] + "'s email: " + people.emails[2] + " phone number: " + people.phonenums[2]);
  default:
    alert("I don't know that person.");
}

Why does this happen?

Body:
Because you don't have any break in your switch cases.

Check the documentation for the switch statement on MDN. It says the following about break (emphasis mine)

The optional break statement associated with each case label ensures that the program breaks out of switch once the matched statement is executed and continues execution at the statement following switch. If break is omitted, the program continues execution at the next statement in the switch statement.

So update your cases to look like

case people.names[0]:
  alert(people.names[0] + "'s email: " + people.emails[0] + " phone number: " + people.phonenums[0]);
  break;


问:
Getting error in my first flutter app while trying to run
I just tried to run my first hello world app with flutter. But its showing error when emulator selected and run clicked.

Here is my code:

```<code>import "package:flutter/material.dart";

void main()
{
  runApp(

      Center(child:Text("Hello world!", textDirection: TextDirection.ltr) ,)
  );
}
</code>```

and the error i get:

```<code>FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:transformNativeLibsWithMergeJniLibsForDebug'.
> org/apache/commons/codec/binary/Base64

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 13s
Finished with error: Gradle task assembleDebug failed with exit code 1
</code>```

Whats wrong? how do i solve it?

答:
According to this github issue, you just have to add this to your build.gradle file:

```<code> packagingOptions {
     pickFirst 'lib/x86/libc++_shared.so'
     pickFirst 'lib/arm64-v8a/libc++_shared.so'
     pickFirst 'lib/x86_64/libc++_shared.so'
     pickFirst 'lib/armeabi-v7a/libc++_shared.so'
 }
</code>```

Body:
I just tried to run my first hello world app with flutter. But its showing error when emulator selected and run clicked.

Here is my code:

import "package:flutter/material.dart";

void main()
{
  runApp(

      Center(child:Text("Hello world!", textDirection: TextDirection.ltr) ,)
  );
}

and the error i get:

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:transformNativeLibsWithMergeJniLibsForDebug'.
> org/apache/commons/codec/binary/Base64

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 13s
Finished with error: Gradle task assembleDebug failed with exit code 1

Whats wrong? how do i solve it?

Body:
According to this github issue, you just have to add this to your build.gradle file:

 packagingOptions {
     pickFirst 'lib/x86/libc++_shared.so'
     pickFirst 'lib/arm64-v8a/libc++_shared.so'
     pickFirst 'lib/x86_64/libc++_shared.so'
     pickFirst 'lib/armeabi-v7a/libc++_shared.so'
 }


问:
Managing Login Timeout Expired errors against SQL Server
I have the next VB.NET code being executed every hour. The code connects to that server and that database and execute some commands, not only on the database MyDatabase, but also on other databases in the same server.

As the user is a sysadmin, it has admin access to all databases without problem.

Dim ConnStr As String
Dim Conn As SqlConnection
Dim cM As SqlCommand
Try
    ConnStr = "Server=MyServer;Database=MyDatabase;User Id=MyUsername;Password=MyPassword;Connect Timeout=300"
    Dim Conn As New SqlConnection(ConnStr)
    cM = New SqlCommand("", Conn) 'The SQL code comes from an script file (*.sql)
    cM.CommandTimeout = 1800
    cM.Connection = Conn
    Conn.Open()
    cM.ExecuteNonQuery()
Catch eX As Exception
    Dim strError As String = ex.Message
    If Not ex.InnerException Is Nothing Then strError &= " | " & ex.InnerException.Message
    strError = "Connection Timeout: " & Conn.ConnectionTimeout.ToString & " | " & _
        "Command Timeout: " & cM.CommandTimeout.ToString & " | " & _
        strError
    objLogging.LogErrorStep(JobID, JobName, CurrentStepName, strError)
Finally
    If Conn.State = ConnectionState.Open Then Conn.Close()
    Conn.Dispose()
End Try
```

<p>The issue we are experimenting is that some of the runs of this job are failing because of Login Timeout Expired errors:</p>

```Connection Timeout: 300 | Command Timeout: 1800 | TCP Provider: Timeout error [258].
OLE DB provider "SQLNCLI10" for linked server "(null)" returned message "Login timeout expired".
OLE DB provider "SQLNCLI10" for linked server "(null)" returned message "Unable to complete login process due to delay in prelogin response".
```

As you can see in the code, I'm saving the errors in a Logging table, and also saving there the current Connection Timeout and the current Command Timeout.

My surprise is that when I'm checking the errors in my Logging table, I can see the elapsed time between the command started time and the command failed time, and the elapsed time has been only 15 seconds, when my Connection Timeout is set to 300. Look at the next image:

As you can see, the difference between the EventStart and the EventStop is about 15 seconds. If the process fails because of a Connection Timeout, and it is set to 300, the elapsed time should be 300, isn't it?

Thanks for your help and comments.

EDIT 2019-05-31

After wait for one more day having set the Connect Timeout = 300 property in the OPEDATASOURCE connectionString, I got a new Login Timeout Expired this afternoon, also just in 15 seconds (See the image)

答:
The connect timeout and CommandTimeout settings apply to the connection from the client to "MyDatabase".  Since your SQL Command connects to linked servers, those settings will not automatically be transferred and will have to be configured at the SQL Server level.  Note that this change applies immediately and is server wide (T-SQL):

```<code>EXEC sp_configure 'remote login timeout', 300;
GO
RECONFIGURE ;
GO

EXEC sp_configure 'remote query timeout', 1800;
GO
RECONFIGURE ;
GO
</code>```

See these two related MSDN links:

Remote Login Timeout

Remote Query Timeout

Body:
I have the next VB.NET code being executed every hour. The code connects to that server and that database and execute some commands, not only on the database MyDatabase, but also on other databases in the same server.

As the user is a sysadmin, it has admin access to all databases without problem.

Dim ConnStr As String
Dim Conn As SqlConnection
Dim cM As SqlCommand
Try
    ConnStr = "Server=MyServer;Database=MyDatabase;User Id=MyUsername;Password=MyPassword;Connect Timeout=300"
    Dim Conn As New SqlConnection(ConnStr)
    cM = New SqlCommand("", Conn) 'The SQL code comes from an script file (*.sql)
    cM.CommandTimeout = 1800
    cM.Connection = Conn
    Conn.Open()
    cM.ExecuteNonQuery()
Catch eX As Exception
    Dim strError As String = ex.Message
    If Not ex.InnerException Is Nothing Then strError &= " | " & ex.InnerException.Message
    strError = "Connection Timeout: " & Conn.ConnectionTimeout.ToString & " | " & _
        "Command Timeout: " & cM.CommandTimeout.ToString & " | " & _
        strError
    objLogging.LogErrorStep(JobID, JobName, CurrentStepName, strError)
Finally
    If Conn.State = ConnectionState.Open Then Conn.Close()
    Conn.Dispose()
End Try

The issue we are experimenting is that some of the runs of this job are failing because of Login Timeout Expired errors:

Connection Timeout: 300 | Command Timeout: 1800 | TCP Provider: Timeout error [258].
OLE DB provider "SQLNCLI10" for linked server "(null)" returned message "Login timeout expired".
OLE DB provider "SQLNCLI10" for linked server "(null)" returned message "Unable to complete login process due to delay in prelogin response".

As you can see in the code, I'm saving the errors in a Logging table, and also saving there the current Connection Timeout and the current Command Timeout.

My surprise is that when I'm checking the errors in my Logging table, I can see the elapsed time between the command started time and the command failed time, and the elapsed time has been only 15 seconds, when my Connection Timeout is set to 300. Look at the next image:

As you can see, the difference between the EventStart and the EventStop is about 15 seconds. If the process fails because of a Connection Timeout, and it is set to 300, the elapsed time should be 300, isn't it?

Thanks for your help and comments.

EDIT 2019-05-31

After wait for one more day having set the Connect Timeout = 300 property in the OPEDATASOURCE connectionString, I got a new Login Timeout Expired this afternoon, also just in 15 seconds (See the image)

Body:
The connect timeout and CommandTimeout settings apply to the connection from the client to "MyDatabase".  Since your SQL Command connects to linked servers, those settings will not automatically be transferred and will have to be configured at the SQL Server level.  Note that this change applies immediately and is server wide (T-SQL):

EXEC sp_configure 'remote login timeout', 300;
GO
RECONFIGURE ;
GO

EXEC sp_configure 'remote query timeout', 1800;
GO
RECONFIGURE ;
GO

See these two related MSDN links:

Remote Login Timeout

Remote Query Timeout


问:
Using BigQuery to visualize high volume of points
At a certain scale of geographic data, it is useful to export the dataset to a png file in order to lay it on top of a map if there are lots of points. For example, if there are 50M points, if we are just interested in visualizing that data (without sampling, re-sampling, or aggregating), we could export that to a png and overlay that onto a map.

An example of this is done with MapD, a GPU database. For example, they will render the image server-side, https://www.omnisci.com/platform/core#native-geospatial-processing, and then send it back to the client:

```<code>blob:https://www.omnisci.com/3cf6df03-4809-4a6d-9b73-24c12c3fadb5
</code>```

Is there any option to do something similar in BigQuery? What would be the suggested way to graph a larger number of geographic points/objects on a map (without going the short route of clustering: https://developers.google.com/maps/documentation/javascript/markers).

答:
BigQuery Geo Viz is the tool for visualization of geospatial data in BigQuery. However, as you already read in @GrahamPolley 's link the limit is only 2,000 results.

So, currently, there is no way to visualize 50M points on a map using BigQuery and Geo Viz.

Off the top of my head, you could export the points from BigQuery and then visualize them with a visualization library of your preferred programming language. However, you would also need to invoke the Maps API so it’s not very feasible as it is like suggesting to develop your own Geo Viz tool.

I have created a feature request for you here which I recommend that you star to receive updates and comment to show that there is interest and provide some traction.

Another option would be to open a support case and ask for a higher limit, although I am not confident that you are going to be provided with, considering the nature of the limit.

Body:
At a certain scale of geographic data, it is useful to export the dataset to a png file in order to lay it on top of a map if there are lots of points. For example, if there are 50M points, if we are just interested in visualizing that data (without sampling, re-sampling, or aggregating), we could export that to a png and overlay that onto a map.

An example of this is done with MapD, a GPU database. For example, they will render the image server-side, https://www.omnisci.com/platform/core#native-geospatial-processing, and then send it back to the client:

blob:https://www.omnisci.com/3cf6df03-4809-4a6d-9b73-24c12c3fadb5

Is there any option to do something similar in BigQuery? What would be the suggested way to graph a larger number of geographic points/objects on a map (without going the short route of clustering: https://developers.google.com/maps/documentation/javascript/markers).


问:
How can I combine numeric values of similar strings?
I have a list of licenses and associated license counts, for example:

```<code>1 Third Party SIP Device Seat
1 Third Party SIP Device Seat
1 Third Party SIP Device Seat
3 Station
3 Station
3 Station
20 Station
</code>```

The lists are never in the same order and I simply need to add the totals for each license type so in the example I would want the return:

```<code>3 Third Party SIP Device Seat
29 Station
</code>```

The data is being entered into unsaved notepad and later moved into a database. Using excel isn't applicable as it's spaces between the numbers and names, not tabs.

What would be the easiest way to accomplish this task?

答:
Here's a super ugly solution:</p>

```<code>from functools import reduce
from collections import defaultdict

lines = [       # replace with e.g: with open('input.txt', 'r') as f: lines = f.readlines()
  "1 Third Party SIP Device Seat",
  "1 Third Party SIP Device Seat",
  "1 Third Party SIP Device Seat",
  "3 Station",
  "3 Station",
  "3 Station",
  "20 Station"
]

def f(acc, x):
  acc[" ".join(x.split(" ")[1:])] += int(x.split(" ")[0]) # first element is the count, everything after we use as "key"
  return acc

r = dict(reduce(f, lines, defaultdict(int)))

print(r)
# {'Third Party SIP Device Seat': 3, 'Station': 29}

# to write to file:
with open("output.txt", "w") as f:
  for k, v in r.items():
    f.write(str(v) + " " + str(k))
</code>```

Body:
I have a list of licenses and associated license counts, for example:

1 Third Party SIP Device Seat
1 Third Party SIP Device Seat
1 Third Party SIP Device Seat
3 Station
3 Station
3 Station
20 Station

The lists are never in the same order and I simply need to add the totals for each license type so in the example I would want the return:

3 Third Party SIP Device Seat
29 Station

The data is being entered into unsaved notepad and later moved into a database. Using excel isn't applicable as it's spaces between the numbers and names, not tabs.

What would be the easiest way to accomplish this task?

Body:
Here's a super ugly solution:

from functools import reduce
from collections import defaultdict

lines = [       # replace with e.g: with open('input.txt', 'r') as f: lines = f.readlines()
  "1 Third Party SIP Device Seat",
  "1 Third Party SIP Device Seat",
  "1 Third Party SIP Device Seat",
  "3 Station",
  "3 Station",
  "3 Station",
  "20 Station"
]

def f(acc, x):
  acc[" ".join(x.split(" ")[1:])] += int(x.split(" ")[0]) # first element is the count, everything after we use as "key"
  return acc

r = dict(reduce(f, lines, defaultdict(int)))

print(r)
# {'Third Party SIP Device Seat': 3, 'Station': 29}

# to write to file:
with open("output.txt", "w") as f:
  for k, v in r.items():
    f.write(str(v) + " " + str(k))


答: You need to provide a break statement</p>

Title: Switch statement default always showing default

Body: You need to provide a break statement


问:
Stop a youtube video playing through the ShockwaveFlash interface
I am playing youtube videos with the TShockwaveFlash component in Delphi 2007.

The component has many options such as play, stop, rewind, gotoFrame, etc and they work on a normal flash file.

However if I try to use them on a youtube video it doesn't work.

Does anyone know if this is just the case, if there is something that needs set for this to work, or if there is another way to exercise control over the playback?

答:
To stop the video from playing you need to make use of the keyboard commands the you tube player recognizes to control the player. They are limited...

```<code> Spacebar   : Play / Pause
 Arrow Left : Jump back 10% in the current video
 Arrow Right: Jump ahead 10% in the current video
 Arrow Up   : Volume up
 Arrow Down : Volume Down
</code>```

So what you can do is use

```<code> SendMessage(FlashPlayer.Handle,WM_KEYDOWN,VK_SPACE,0);
 SendMessage(FlashPlayer.Handle,WM_KEYUP,VK_SPACE,0);
</code>```

to fake a key press and get the youtube player to, in this example, pause or resume play.

ContentLicense: CC BY-SA 2.5

Body:
To stop the video from playing you need to make use of the keyboard commands the you tube player recognizes to control the player. They are limited...

 Spacebar   : Play / Pause
 Arrow Left : Jump back 10% in the current video
 Arrow Right: Jump ahead 10% in the current video
 Arrow Up   : Volume up
 Arrow Down : Volume Down

So what you can do is use

 SendMessage(FlashPlayer.Handle,WM_KEYDOWN,VK_SPACE,0);
 SendMessage(FlashPlayer.Handle,WM_KEYUP,VK_SPACE,0);

to fake a key press and get the youtube player to, in this example, pause or resume play.

ContentLicense: CC BY-SA 3.0


问:
How can I plot X,Y coordinates by added order?
I want to connect X and Y coordinates by order which I inputed to make a circle .

I found a program that draw X,Y coordinates in Java .
Then I added my data of circle but program connected nearest X,Y coordinates not ordered X,Y .

```<code>public Graph(final String title) {

    super(title);
    final XYSeries series = new XYSeries("Random Data");

    series.add(2.000 , 0);
    series.add(0 , 2.000);
    series.add(-2.000 , 0);
    series.add(0 , -2.000);
    final XYSeriesCollection data = new XYSeriesCollection(series);
    final JFreeChart chart = ChartFactory.createXYLineChart(
            "XY Series Demo",
            "X",
            "Y",
            data,
            PlotOrientation.VERTICAL,
            true,
            true,
            false
    );
</code>```

I expected results as square diagram .

答:
The XYSeries API specifies,

By default, items in the series will be sorted into ascending order by x-value, and duplicate x-values are permitted.

You can defeat this with the appropriate constructor, suggested here:

```<code>final XYSeries series = new XYSeries("Random Data", false);
</code>```

In the illustration below, I've added  an extra data point to close the figure:

For arbitrary shapes, also consider an XYShapeAnnotation, seen here.

Body:
I want to connect X and Y coordinates by order which I inputed to make a circle .

I found a program that draw X,Y coordinates in Java .
Then I added my data of circle but program connected nearest X,Y coordinates not ordered X,Y .

public Graph(final String title) {

    super(title);
    final XYSeries series = new XYSeries("Random Data");

    series.add(2.000 , 0);
    series.add(0 , 2.000);
    series.add(-2.000 , 0);
    series.add(0 , -2.000);
    final XYSeriesCollection data = new XYSeriesCollection(series);
    final JFreeChart chart = ChartFactory.createXYLineChart(
            "XY Series Demo",
            "X",
            "Y",
            data,
            PlotOrientation.VERTICAL,
            true,
            true,
            false
    );

I expected results as square diagram .

Body:
The XYSeries API specifies,

By default, items in the series will be sorted into ascending order by x-value, and duplicate x-values are permitted.

You can defeat this with the appropriate constructor, suggested here:

final XYSeries series = new XYSeries("Random Data", false);

In the illustration below, I've added  an extra data point to close the figure:

For arbitrary shapes, also consider an XYShapeAnnotation, seen here.


问:
Angular 7 PDFJS Component
I'm trying to wrap up PDFJS inside of an Angular 7 component.  I have the following code, but PDFJS is undefined.  I'm building the app using Angular/CLI.

```<code>import { Component, OnInit, ElementRef, ViewChild, Input } from '@angular/core';
declare let PDFJS: any;

@Component({
  selector: 'app-dsgpdf',
  templateUrl: './dsgpdf.component.html',
  styleUrls: ['./dsgpdf.component.scss']
})
export class DsgpdfComponent implements OnInit {
    @ViewChild('theCanvas', { read: ElementRef }) theCanvas;

    constructor() {

    }

    ngOnInit() {
        debugger;
        //
        // If absolute URL from the remote server is provided, configure the CORS
        // header on that server.
        //
        var url = '/assets/fdcc0545-a0d7-4c30-89ef-5a908a1e2a47.pdf';
        //
        // The workerSrc property shall be specified.
        //

        let pdfWorkerSrc: string = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.0.943/pdf.worker.min.js';

        PDFJS.GlobalWorkerOptions.workerSrc = pdfWorkerSrc;
        //
        // Asynchronous download PDF
        //
        var loadingTask = PDFJS.getDocument(url);
        loadingTask.then(pdf => {
            //
            // Fetch the first page
            //
            pdf.getPage(2).then(page => {
                var scale = 1.5;
                var viewport = page.getViewport(scale);
                //
                // Prepare canvas using PDF page dimensions
                //
                var canvas = this.theCanvas.nativeElement;
                var context = canvas.getContext('2d');
                canvas.height = viewport.height;
                canvas.width = viewport.width;
                //
                // Render PDF page into canvas context
                //
                var renderContext = {
                    canvasContext: context,
                    viewport: viewport,
                };
                page.render(renderContext).then(() => {
                    debugger;
                });
            });
        });
  }

}
</code>```

I've also tried adding this line of code:

```<code>let PDFJS: any = require('pdfjs-dist/build/pdf');
</code>```

But, it fails to compile:

```<code> error TS2580: Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i @types/node`.
</code>```

I'm clearly importing this incorrectly.  Can someone point me in the right direction.

Secondary question:  I don't want to load the worker from a cdn.  What's the right way to do this when using Angular/CLI?

答:
There are no targeted angular components for PDFJS. Configuration needs extra steps and not very straight forward. If you are willing to bring an extra angular npm package, Here are few packages the open source community has created as alternatives.

The below package will help you integrate pdfjs into your angular 7. It does provide the base functionality, does not provide a viewer. Highly configurable: ng2-pdf-viewer.

```<code> import { Component } from '@angular/core';
 @Component({
  selector: 'example-app',
  template: `
  <div>
      <label>PDF src</label>
      <input type="text" placeholder="PDF src" [(ngModel)]="pdfSrc">
  </div>
  <pdf-viewer [src]="pdfSrc"
              [render-text]="true"
              style="display: block;"
  ></pdf-viewer>
  `
})
export class AppComponent {
  pdfSrc: string = '/pdf-test.pdf';
}
</code>```

Also, there is another package - ng2-pdfjs-viewer which provides a viewer as well - full disclosure, it is created by me.

Usage is like this.

```<code><!-- your.component.html -->
<button (click)="openPdf();">Open Pdf</button>

<ng2-pdfjs-viewer #pdfViewer style="width: 800px; height: 400px"
  [pdfJsFolder]="'pdfjs'"
  [externalWindow]="true"
  [downloadFileName]="'mytestfile.pdf'"
  [download]="false">
</ng2-pdfjs-viewer>

<!-- your.component.ts-->
export class RateCardComponent implements OnInit {
  @ViewChild('pdfViewer') pdfViewer;
  ...

  private downloadFile(url: string): any {
    return this.http.get(url, { responseType: ResponseContentType.Blob }).map(
      (res) => {
        return new Blob([res.blob()], { type: "application/pdf" });
      });
  }

  public openPdf() {
    let url = "url to fetch pdf as byte array";
    // url can be local url or remote http request to an api/pdf file.
    // E.g: let url = "assets/pdf-sample.pdf";
    // E.g: https://github.com/intbot/ng2-pdfjs-viewer/tree/master/sampledoc/pdf-sample.pdf
    // E.g: http://localhost:3000/api/GetMyPdf
    // Please note, for remote urls to work, CORS should be enabled at the server. Read: https://enable-cors.org/server.html

    this.downloadFile(url).subscribe(
      (res) => {
        this.pdfViewer.pdfSrc = res; // pdfSrc can be Blob or Uint8Array
      }
    );
  }
</code>```

Title: Angular 7 PDFJS Component

Body:
I'm trying to wrap up PDFJS inside of an Angular 7 component.  I have the following code, but PDFJS is undefined.  I'm building the app using Angular/CLI.

import { Component, OnInit, ElementRef, ViewChild, Input } from '@angular/core';
declare let PDFJS: any;

@Component({
  selector: 'app-dsgpdf',
  templateUrl: './dsgpdf.component.html',
  styleUrls: ['./dsgpdf.component.scss']
})
export class DsgpdfComponent implements OnInit {
    @ViewChild('theCanvas', { read: ElementRef }) theCanvas;

    constructor() {

    }

    ngOnInit() {
        debugger;
        //
        // If absolute URL from the remote server is provided, configure the CORS
        // header on that server.
        //
        var url = '/assets/fdcc0545-a0d7-4c30-89ef-5a908a1e2a47.pdf';
        //
        // The workerSrc property shall be specified.
        //

        let pdfWorkerSrc: string = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.0.943/pdf.worker.min.js';

        PDFJS.GlobalWorkerOptions.workerSrc = pdfWorkerSrc;
        //
        // Asynchronous download PDF
        //
        var loadingTask = PDFJS.getDocument(url);
        loadingTask.then(pdf => {
            //
            // Fetch the first page
            //
            pdf.getPage(2).then(page => {
                var scale = 1.5;
                var viewport = page.getViewport(scale);
                //
                // Prepare canvas using PDF page dimensions
                //
                var canvas = this.theCanvas.nativeElement;
                var context = canvas.getContext('2d');
                canvas.height = viewport.height;
                canvas.width = viewport.width;
                //
                // Render PDF page into canvas context
                //
                var renderContext = {
                    canvasContext: context,
                    viewport: viewport,
                };
                page.render(renderContext).then(() => {
                    debugger;
                });
            });
        });
  }

}

I've also tried adding this line of code:

let PDFJS: any = require('pdfjs-dist/build/pdf');

But, it fails to compile:

 error TS2580: Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i @types/node`.

I'm clearly importing this incorrectly.  Can someone point me in the right direction.

Secondary question:  I don't want to load the worker from a cdn.  What's the right way to do this when using Angular/CLI?

Body:
There are no targeted angular components for PDFJS. Configuration needs extra steps and not very straight forward. If you are willing to bring an extra angular npm package, Here are few packages the open source community has created as alternatives.

The below package will help you integrate pdfjs into your angular 7. It does provide the base functionality, does not provide a viewer. Highly configurable: ng2-pdf-viewer.

 import { Component } from '@angular/core';
 @Component({
  selector: 'example-app',
  template: `
  <div>
      <label>PDF src</label>
      <input type="text" placeholder="PDF src" [(ngModel)]="pdfSrc">
  </div>
  <pdf-viewer [src]="pdfSrc"
              [render-text]="true"
              style="display: block;"
  ></pdf-viewer>
  `
})
export class AppComponent {
  pdfSrc: string = '/pdf-test.pdf';
}

Also, there is another package - ng2-pdfjs-viewer which provides a viewer as well - full disclosure, it is created by me.

Usage is like this.

<!-- your.component.html -->
<button (click)="openPdf();">Open Pdf</button>

<ng2-pdfjs-viewer #pdfViewer style="width: 800px; height: 400px"
  [pdfJsFolder]="'pdfjs'"
  [externalWindow]="true"
  [downloadFileName]="'mytestfile.pdf'"
  [download]="false">
</ng2-pdfjs-viewer>

<!-- your.component.ts-->
export class RateCardComponent implements OnInit {
  @ViewChild('pdfViewer') pdfViewer;
  ...

  private downloadFile(url: string): any {
    return this.http.get(url, { responseType: ResponseContentType.Blob }).map(
      (res) => {
        return new Blob([res.blob()], { type: "application/pdf" });
      });
  }

  public openPdf() {
    let url = "url to fetch pdf as byte array";
    // url can be local url or remote http request to an api/pdf file.
    // E.g: let url = "assets/pdf-sample.pdf";
    // E.g: https://github.com/intbot/ng2-pdfjs-viewer/tree/master/sampledoc/pdf-sample.pdf
    // E.g: http://localhost:3000/api/GetMyPdf
    // Please note, for remote urls to work, CORS should be enabled at the server. Read: https://enable-cors.org/server.html

    this.downloadFile(url).subscribe(
      (res) => {
        this.pdfViewer.pdfSrc = res; // pdfSrc can be Blob or Uint8Array
      }
    );
  }


问:
While loops with dependent If statements in Python
I have a program that creates binary numbers from base 10 numbers base on n. I use t as a counter for my while loop.

I am trying to fill a list with the output from this so nmust equal t. How can I do this without undermining my while loop and if statements?

```<code>keyList = []
binList = []
n = 0
i = 0
t = 0

while (t <= 255):
    ## 128
    if n < 128:
        binList.append(0)
        n = n

    elif n >= 128:
        binList.append(1)
        n = n - 128

    ## 64
    if n < 64:
        binList.append(0)
        n = n

    elif n >= 64:
        binList.append(1)
        n = n - 64

    ## 32
    if n < 32:
        binList.append(0)
        n = n

    elif n >= 32:
        binList.append(1)
        n = n - 32

    ## 16
    if n < 16:
        binList.append(0)
        n = n

    elif n >= 16:
        binList.append(1)
        n = n -16

    ## 8
    if n < 8:
        binList.append(0)
        n = n

    elif n >= 8:
        binList.append(1)
        n = n - 8

    ## 4
    if n < 4:
        binList.append(0)
        n = n

    elif n >= 4:
        binList.append(1)
        n = n - 4

    ## 2
    if n < 2:
        binList.append(0)
        n = n

    elif n >= 2:
        binList.append(1)
        n = n - 2

    ## 1
    if n < 1:
        binList.append(0)
        n = n

    elif n >= 1:
        binList.append(1)
        n = n - 1
    print(n)
    t = t + 1
</code>```

Currently, I am not able to get n and t to equal each other without impacting the outcome of the code where I only get 0.

答:
The loop style that you have above is not exactly pythonic. for t in range(x) is a typical way to iterate through a range of numbers.  You have effectively unrolled a loop into a series of highly repetitive if statements, which I've rolled up into an inner list. n must be initialized for each value of t, and lastly I took the next step to add the binary string to the keyList.

keyList = []
binList = []
n = 0
i = 0

value_list = [128, 64, 32, 16, 8, 4, 2, 1]
for t in range(255): # iterates through 0 to 255
    n = t
    binList = []
    for v in value_list: # iterates over list in order
        if n < v:
            bit = 0
        else:
            bit = 1
            n = n - v
        binList.append(bit)
    keyList.append("".join(map(str, binList)))
```

Body:
I have a program that creates binary numbers from base 10 numbers base on n. I use t as a counter for my while loop.

I am trying to fill a list with the output from this so nmust equal t. How can I do this without undermining my while loop and if statements?

keyList = []
binList = []
n = 0
i = 0
t = 0

while (t <= 255):
    ## 128
    if n < 128:
        binList.append(0)
        n = n

    elif n >= 128:
        binList.append(1)
        n = n - 128

    ## 64
    if n < 64:
        binList.append(0)
        n = n

    elif n >= 64:
        binList.append(1)
        n = n - 64

    ## 32
    if n < 32:
        binList.append(0)
        n = n

    elif n >= 32:
        binList.append(1)
        n = n - 32

    ## 16
    if n < 16:
        binList.append(0)
        n = n

    elif n >= 16:
        binList.append(1)
        n = n -16

    ## 8
    if n < 8:
        binList.append(0)
        n = n

    elif n >= 8:
        binList.append(1)
        n = n - 8

    ## 4
    if n < 4:
        binList.append(0)
        n = n

    elif n >= 4:
        binList.append(1)
        n = n - 4

    ## 2
    if n < 2:
        binList.append(0)
        n = n

    elif n >= 2:
        binList.append(1)
        n = n - 2

    ## 1
    if n < 1:
        binList.append(0)
        n = n

    elif n >= 1:
        binList.append(1)
        n = n - 1
    print(n)
    t = t + 1

Currently, I am not able to get n and t to equal each other without impacting the outcome of the code where I only get 0.


问:
Trouble pre-selecting value coming from database in HTML select
I've got partially working code to select the correct value coming from MySql/PHP in a drop down.

```<code>jQuery( document ).ready( function ( $ ) {
  $( '#hosp_country' ).find( 'option[value=<?php echo $tE['hosp_country']; ?>]' ).attr( 'selected', 'selected' );
   } );
</code>```

If the value - $tE['hosp_country'] - is a single word, everything works properly and the correct value is selected in the select - "Argentina" or "Armenia", for example.

If the value is more than one word with a space, the value isn't selected. "Bovet Island" or "Czech Republic", for example.

What do I have incorrect?

答:
The problem in your code is that you're not enclosing your value attribute's value with double quotes inside your jquery attribute selector.

Correct code is below:

```<code>jQuery( document ).ready( function ( $ ) {
  $( '#hosp_country' ).find( 'option[value="<?php echo $tE['hosp_country']; ?>"]' ).attr( 'selected', 'selected' );
});
</code>```

But there's a better way of doing what you want. just give the value you want to the select input, and that's all.

$(document).ready(() => {
  // Give the value to select input
  $('#hosp_country').val('Czech Republic');
  // With php, your code should look like:
  // $('#hosp_country').val('<?php echo $tE['hosp_country']; ?>');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<select id="hosp_country">
  <option>Argentina</option>
  <option>Armenia</option>
  <option>Czech Republic</option>
  <option>Bovet Island</option>
</select></code>```

Body:
I've got partially working code to select the correct value coming from MySql/PHP in a drop down.

jQuery( document ).ready( function ( $ ) {
  $( '#hosp_country' ).find( 'option[value=<?php echo $tE['hosp_country']; ?>]' ).attr( 'selected', 'selected' );
   } );

If the value - $tE['hosp_country'] - is a single word, everything works properly and the correct value is selected in the select - "Argentina" or "Armenia", for example.

If the value is more than one word with a space, the value isn't selected. "Bovet Island" or "Czech Republic", for example.

What do I have incorrect?

Body:
The problem in your code is that you're not enclosing your value attribute's value with double quotes inside your jquery attribute selector.

Correct code is below:

jQuery( document ).ready( function ( $ ) {
  $( '#hosp_country' ).find( 'option[value="<?php echo $tE['hosp_country']; ?>"]' ).attr( 'selected', 'selected' );
});

But there's a better way of doing what you want. just give the value you want to the select input, and that's all.

$(document).ready(() => {
  // Give the value to select input
  $('#hosp_country').val('Czech Republic');
  // With php, your code should look like:
  // $('#hosp_country').val('<?php echo $tE['hosp_country']; ?>');
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<select id="hosp_country">
  <option>Argentina</option>
  <option>Armenia</option>
  <option>Czech Republic</option>
  <option>Bovet Island</option>
</select>


问:
Can't able to run a Task in Airflow
Whenever I tried to run my DAG it gets success state but it can't able to run the task.
While running the first time it works perfectly

trigger_controller_dag.py:

```<code>def conditionally_trigger(context, dag_run_obj):
    c_p = context['params']['condition_param']
    if context['params']['condition_param']:
        dag_run_obj.payload = {'message': context['params']['message']}
        pp.pprint(dag_run_obj.payload)
        return dag_run_obj

dag = DAG(
    dag_id='example_trigger_controller_dag',
    default_args={
        "owner": "airflow",
        "start_date": datetime.utcnow(),
    },
    schedule_interval='@once',
)

trigger = TriggerDagRunOperator(
    task_id='test_trigger_dagrun',
    trigger_dag_id="example_trigger_target_dag",
    python_callable=conditionally_trigger,
    params={'condition_param': True, 'message': 'Hello World'},
    dag=dag,
)
</code>```

trigger_target_dag.py:

```<code>args = {
    'start_date': datetime.utcnow(),
    'owner': 'airflow',
}

dag = DAG(
    dag_id='example_trigger_target_dag',
    default_args=args,
    schedule_interval=None,
)

def run_this_func(ds, **kwargs):
    print("Remotely received value of {} for key=message".
          format(kwargs['dag_run'].conf['message']))

run_this = PythonOperator(
    task_id='run_this',
    provide_context=True,
    python_callable=run_this_func,
    dag=dag,
)
</code>```

While running the DAG I am getting the following error,
dependency 'Task Instance State' FAILED: Task is in the 'success' state which is not a valid state for execution. The task must be cleared in order to be run

答:
Your start_date variables in both DAGS are dynamic and may be causing your problem 'start_date': datetime.utcnow(). Setting them to a dynamic start is not recommended and leads to errors.

Try setting it to a static start date like 'start_date': datetime(2019, 5, 29) #year month day

Taken from Airflow FAQ

We recommend against using dynamic values as start_date, especially
  datetime.now() as it can be quite confusing. The task is triggered
  once the period closes, and in theory an @hourly DAG would never get
  to an hour after now as now() moves along.

Another SO question on this: why dynamic start causes issues

Title: Can't able to run a Task in Airflow

Body:
Whenever I tried to run my DAG it gets success state but it can't able to run the task.
While running the first time it works perfectly

trigger_controller_dag.py:

def conditionally_trigger(context, dag_run_obj):
    c_p = context['params']['condition_param']
    if context['params']['condition_param']:
        dag_run_obj.payload = {'message': context['params']['message']}
        pp.pprint(dag_run_obj.payload)
        return dag_run_obj

dag = DAG(
    dag_id='example_trigger_controller_dag',
    default_args={
        "owner": "airflow",
        "start_date": datetime.utcnow(),
    },
    schedule_interval='@once',
)

trigger = TriggerDagRunOperator(
    task_id='test_trigger_dagrun',
    trigger_dag_id="example_trigger_target_dag",
    python_callable=conditionally_trigger,
    params={'condition_param': True, 'message': 'Hello World'},
    dag=dag,
)

trigger_target_dag.py:

args = {
    'start_date': datetime.utcnow(),
    'owner': 'airflow',
}

dag = DAG(
    dag_id='example_trigger_target_dag',
    default_args=args,
    schedule_interval=None,
)

def run_this_func(ds, **kwargs):
    print("Remotely received value of {} for key=message".
          format(kwargs['dag_run'].conf['message']))

run_this = PythonOperator(
    task_id='run_this',
    provide_context=True,
    python_callable=run_this_func,
    dag=dag,
)

While running the DAG I am getting the following error,
dependency 'Task Instance State' FAILED: Task is in the 'success' state which is not a valid state for execution. The task must be cleared in order to be run


问:
Enter and exit browser fullscreen view with Javascript on pressing a key
I have an element I want to show full-screen when the user presses the f-key.

My HTML

```<code><div id="test">
   hello
</div>
</code>```

My JS

```<code>// go fullscreen when pressing 'f' (key 70)
document.onkeydown = function(e){
    e = e || window.event;
    var key = e.which || e.keyCode;
    if(key===70){
        requestFullScreen(
            document.getElementById("test")
        );
    }
};

function requestFullScreen(elt) {
    console.log("Requesting fullscreen for", elt);
    if (elt.requestFullscreen) {
        elt.requestFullscreen();
    } else if (elt.msRequestFullscreen) {
        elt.msRequestFullscreen();
    } else if (elt.mozRequestFullScreen) {
        elt.mozRequestFullScreen();
    } else if (elt.webkitRequestFullscreen) {
        elt.webkitRequestFullscreen();
    } else {
        console.error("Fullscreen not available");
    }
}
</code>```

or a JSFiddle.

Opening the element full-screen is working. My question: how to close full-screen when the user presses 'f' whenever full-screen is opened? I imagine I need to test whether or not the current view is full-screen or not, and depending on the outcome make the key press event behave differently. How though?

答:
You can check whether or not the document is in fullscreen mode by using the boolean value document.fullscreen. To exit fullscreen you use document.exitFullscreen().

Fiddle that works in Chrome: https://jsfiddle.net/weft_digital/wrd4yo5s/1/

```<code>document.onkeydown = function(e){
  e = e || window.event;
  var key = e.which || e.keyCode;
  if(key===70){
       if(!document.fullscreenElement){
            requestFullScreen(document.getElementById("test"));
        }else{
            document.exitFullscreen()
        }
    }
};
</code>```

Body:
I have an element I want to show full-screen when the user presses the f-key.

My HTML

   hello

My JS

// go fullscreen when pressing 'f' (key 70)
document.onkeydown = function(e){
    e = e || window.event;
    var key = e.which || e.keyCode;
    if(key===70){
        requestFullScreen(
            document.getElementById("test")
        );
    }
};

function requestFullScreen(elt) {
    console.log("Requesting fullscreen for", elt);
    if (elt.requestFullscreen) {
        elt.requestFullscreen();
    } else if (elt.msRequestFullscreen) {
        elt.msRequestFullscreen();
    } else if (elt.mozRequestFullScreen) {
        elt.mozRequestFullScreen();
    } else if (elt.webkitRequestFullscreen) {
        elt.webkitRequestFullscreen();
    } else {
        console.error("Fullscreen not available");
    }
}

or a JSFiddle.

Opening the element full-screen is working. My question: how to close full-screen when the user presses 'f' whenever full-screen is opened? I imagine I need to test whether or not the current view is full-screen or not, and depending on the outcome make the key press event behave differently. How though?

Body:
You can check whether or not the document is in fullscreen mode by using the boolean value document.fullscreen. To exit fullscreen you use document.exitFullscreen().

Fiddle that works in Chrome: https://jsfiddle.net/weft_digital/wrd4yo5s/1/

document.onkeydown = function(e){
  e = e || window.event;
  var key = e.which || e.keyCode;
  if(key===70){
       if(!document.fullscreenElement){
            requestFullScreen(document.getElementById("test"));
        }else{
            document.exitFullscreen()
        }
    }
};


问:
Axios on Nodejs wont retain session on requested server while PostMan does
I am able to do the following on PostMan

1) POST method to login to company server.
2) Make other requests as a logged in user on company server.

I have created a nodejs app to communicate with the company server.
I am using axios library to make said communications.

after Logging in to company server, any other calls don't recognize me as an authorized user.

What could be the differences that i could in turn recreate on axios to have that session persistance?

答:
In the browser you use withCredentials in axios - this option automatically saves your session between requests. But in node.js this parameter does not work because axios uses the http node.js module instead of XHR.

In node.js, you can use an axios instance for save cookie between requests.

Simplest way is:

Create instance

```<code>const BASE_URL = "https://stackoverflow.com";

// Create instance of axios which utilizes BASE_URL
const axiosInstance = axios.create({ baseURL: BASE_URL });
</code>```

Write createSession function

```<code>const createSession = async () => {
  console.log("create session");
  const authParams = {
    username: "username",
    password: "password"
  };
  const resp = await axios.post(BASE_URL, authParams);
  const cookie = resp.headers["set-cookie"][0]; // get cookie from request
  axiosInstance.defaults.headers.Cookie = cookie;   // attach cookie to axiosInstance for future requests
};
</code>```

And make call with session cookie

```<code>// send Post request to https://stackoverflow.com/protected after created session
createSession().then(() => {
  axiosInstance.post('/protected') // with new cookie
})
</code>```

Be careful, your authorization method may differ from the presented - in this case you can just change the createSession method. If your session has expired, you can login again directly or using axios.interceptors - I attached a link to gist.

Also you can use cookie-jar with axios (link below)

For more info:

https://github.com/axios/axios#creating-an-instance

https://github.com/axios/axios#interceptors

https://gist.github.com/nzvtrk/ebf494441e36200312faf82ce89de9f2

https://github.com/3846masa/axios-cookiejar-support

Body:
In the browser you use withCredentials in axios - this option automatically saves your session between requests. But in node.js this parameter does not work because axios uses the http node.js module instead of XHR.

In node.js, you can use an axios instance for save cookie between requests.

Simplest way is:

Create instance

const BASE_URL = "https://stackoverflow.com";

// Create instance of axios which utilizes BASE_URL
const axiosInstance = axios.create({ baseURL: BASE_URL });

Write createSession function

const createSession = async () => {
  console.log("create session");
  const authParams = {
    username: "username",
    password: "password"
  };
  const resp = await axios.post(BASE_URL, authParams);
  const cookie = resp.headers["set-cookie"][0]; // get cookie from request
  axiosInstance.defaults.headers.Cookie = cookie;   // attach cookie to axiosInstance for future requests
};

And make call with session cookie

// send Post request to https://stackoverflow.com/protected after created session
createSession().then(() => {
  axiosInstance.post('/protected') // with new cookie
})

Be careful, your authorization method may differ from the presented - in this case you can just change the createSession method. If your session has expired, you can login again directly or using axios.interceptors - I attached a link to gist.

Also you can use cookie-jar with axios (link below)

For more info:

https://github.com/axios/axios#creating-an-instance

https://github.com/axios/axios#interceptors

https://gist.github.com/nzvtrk/ebf494441e36200312faf82ce89de9f2

https://github.com/3846masa/axios-cookiejar-support


问:
Bulk Text Editing
How can I add certain character to the END of each row? With same spacing in between old and new column values across rows!

I tried shift+Alt to select multiple rows and using search --> Regular Expression --> $ Command I can bring cursor to end of each line irrespective of Size of each word.

But How to merge new column values near existing Column values with unique alignment across rows.

Is it possible in Notepad ++

```<code>Column 1 :

action
usersessionid*
token
accountid
clientip

Column 2 :

Dinesh
Kishore
Yuva
Vignesh
Ganesh
</code>```

Expected---------------

```<code>Merged Column :
action Dinesh
usersessionid* Kishore
token Yuva
accountid Vignesh
clientip Ganesh
</code>```

答:
When you've selected the values of "Column 2" with Shift+Alt+Mouse drag:

just copy the values Ctrl+C

select a column right after the values in "Column 1" with Shift+Alt+Mouse drag

paste Ctrl+V

delete the superfluous spaces with:

Ctrl+H

Find what: \h{2,}

Replace with:          # a space

Replace all

Title: Bulk Text Editing

Body:
How can I add certain character to the END of each row? With same spacing in between old and new column values across rows!

I tried shift+Alt to select multiple rows and using search --> Regular Expression --> $ Command I can bring cursor to end of each line irrespective of Size of each word.

But How to merge new column values near existing Column values with unique alignment across rows.

Is it possible in Notepad ++

Column 1 :

action
usersessionid*
token
accountid
clientip

Column 2 :

Dinesh
Kishore
Yuva
Vignesh
Ganesh

Expected---------------

Merged Column :
action Dinesh
usersessionid* Kishore
token Yuva
accountid Vignesh
clientip Ganesh


问:
My reducers keep returning undefined despite the fact that data is being accessed
I am working on a React Native application which has a facebook login feature that is working, the action creator and reducer is working just fine for that, but the action creators and reducers for the job search API I am using is not working.

These are the action creators:

```<code>import axios from "axios";
// import { Location } from "expo";
import qs from "qs";

import { FETCH_JOBS, LIKE_JOB } from "./types";
import locationify from "../tools/locationify";

const JOB_ROOT_URL = "https://authenticjobs.com/api/?";

const JOB_QUERY_PARAMS = {
  api_key: "<api_key>",
  method: "aj.jobs.search",
  perpage: "10",
  format: "json",
  keywords: "javascript"
};

const buildJobsUrl = () => {
  const query = qs.stringify({ ...JOB_QUERY_PARAMS });
  return `${JOB_ROOT_URL}${query}`;
};

export const fetchJobs = (
  region,
  distance = 10,
  callback
) => async dispatch => {
  try {
    const url = buildJobsUrl();
    let job_list = await axios.get(url);
    job_list = locationify(
      region,
      console.log(job_list.data.listings.listing),
      job_list.data.listings.listing,
      distance,
      (obj, coords) => {
        obj.company.location = { ...obj.company.location, coords };
        return obj;
      }
    );
    dispatch({ type: FETCH_JOBS, payload: job_list });
    callback();
  } catch (e) {
    console.log("fetchJobs Action Error:", e.message);
  }
};

export const likeJob = job => {
  return {
    payload: job,
    type: LIKE_JOB
  };
};
</code>```

This is the jobs_reducer.js:

```<code>import { FETCH_JOBS } from "../actions/types";

const INITIAL_STATE = {
  listings: []
};

export default function(state = INITIAL_STATE, action) {
  switch (action.type) {
    case FETCH_JOBS:
      return action.payload;
    default:
      return state;
  }
}
</code>```

This is the likes_reducer.js:

```<code>import _ from "lodash";
import { LIKE_JOB } from "../actions/types";

export default function(state = [], action) {
  switch (action.type) {
    case LIKE_JOB:
      return _.uniqBy([action.payload, ...state], "id");
    default:
      return state;
  }
}
</code>```

I spent all evening yesterday debugging this and all I know is that I am console logging data to my terminal, I can see the details of the jobs API data just populate my terminal, but the error message is that the reducers are returning undefined.

How can I return data and return undefined simultaneously?

I am using an asynchronous action creator. Do I need redux-thunk on a React Native application? Am I using a version of React Native that has a bug right now? I know how Redux is supposed to work and so I am stumped here.

In reducers/index.js:

```<code>import { combineReducers } from "redux";
import auth from "./auth_reducer";
import jobs from "./jobs_reducer";
import likedJobs from "./likes_reducer";

export default combineReducers({
  auth,
  jobs,
  likedJobs
});
</code>```

Where I start to get that error or what the error is referencing is the this.props.data.map() as in the components/Swipe.js:

```<code>import React, { Component } from "react";
import {
  View,
  Animated,
  PanResponder,
  Dimensions,
  LayoutAnimation,
  UIManager
} from "react-native";

const SCREEN_WIDTH = Dimensions.get("window").width;
const SWIPE_THRESHOLD = 0.25 * SCREEN_WIDTH;
const SWIPE_OUT_DURATION = 250;

class Swipe extends Component {
  static defaultProps = {
    onSwipeRight: () => {},
    onSwipeLeft: () => {},
    keyProp: "id"
  };

  constructor(props) {
    super(props);

    const position = new Animated.ValueXY();
    const panResponder = PanResponder.create({
      onStartShouldSetPanResponder: (event, gestureState) => true,
      onPanResponderMove: (event, gestureState) => {
        position.setValue({ x: gestureState.dx, y: gestureState.dy });
      },
      onPanResponderRelease: (event, gestureState) => {
        if (gestureState.dx > SWIPE_THRESHOLD) {
          this.forceSwipe("right");
        } else if (gestureState.dx < -SWIPE_THRESHOLD) {
          this.forceSwipe("left");
        } else {
          this.resetPosition();
        }
      }
    });

    this.state = { panResponder, position, index: 0 };
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.data !== this.props.data) {
      this.setState({ index: 0 });
    }
  }

  componentWillUpdate() {
    UIManager.setLayoutAnimationEnabledExperimental &&
      UIManager.setLayoutAnimationEnabledExperimental(true);
    LayoutAnimation.spring();
  }

  forceSwipe(direction) {
    const x = direction === "right" ? SCREEN_WIDTH : -SCREEN_WIDTH;
    Animated.timing(this.state.position, {
      toValue: { x, y: 0 },
      duration: SWIPE_OUT_DURATION
    }).start(() => this.onSwipeComplete(direction));
  }

  onSwipeComplete(direction) {
    const { onSwipeLeft, onSwipeRight, data } = this.props;
    const item = data[this.state.index];
    direction === "right" ? onSwipeRight(item) : onSwipeLeft(item);
    this.state.position.setValue({ x: 0, y: 0 });
    this.setState({ index: this.state.index + 1 });
  }

  resetPosition() {
    Animated.spring(this.state.position, {
      toValue: { x: 0, y: 0 }
    }).start();
  }

  getCardStyle() {
    const { position } = this.state;
    const rotate = position.x.interpolate({
      inputRange: [-SCREEN_WIDTH * 1.5, 0, SCREEN_WIDTH * 1.5],
      outputRange: ["-120deg", "0deg", "120deg"]
    });
    return {
      ...position.getLayout(),
      transform: [{ rotate }]
    };
  }

  renderCards() {
    if (this.state.index >= this.props.data.length) {
      return this.props.renderNoMoreCards();
    }

    return this.props.data
      .map((item, i) => {
        if (i < this.state.index) {
          return null;
        }

        if (i === this.state.index) {
          return (
            <Animated.View
              key={item[this.props.id]}
              style={[this.getCardStyle(), styles.cardStyle]}
              {...this.state.panResponder.panHandlers}
            >
              {this.props.renderCard(item)}
            </Animated.View>
          );
        }
        return (
          <Animated.View
            key={item[this.props.id]}
            style={[styles.cardStyle, { top: 10 * (i - this.state.index) }]}
          >
            {this.props.renderCard(item)}
          </Animated.View>
        );
      })
      .reverse();
  }

  render() {
    return <View>{this.renderCards()}</View>;
  }
}

const styles = {
  cardStyle: {
    position: "absolute",
    width: SCREEN_WIDTH
  }
};

export default Swipe;
</code>```

Above I am getting that this.props.data.map() is either undefined or is not a function.

I get the same issue in ReviewScreen.js:

```<code>import React, { Component } from "react";
import { View, Text, Button, ScrollView } from "react-native";
import { connect } from "react-redux";

class ReviewScreen extends Component {
  static navigationOptions = ({ navigation }) => ({
    headerTitle: "Review Jobs",
    headerRight: (
      <Button
        title="Settings"
        onPress={() => {
          navigation.navigate("settings");
        }}
      />
    )
  });

  renderLikedJobs() {
    return this.props.likedJobs.map(job => {
      return (
        <Card>
          <View style={{ height: 200 }}>
            <View style={styles.detailWrapper}>
              <Text style={styles.italics}>{job.company}</Text>
              <Text style={styles.italics}>{job.post_date}</Text>
            </View>
          </View>
        </Card>
      );
    });
  }

  render() {
    return <ScrollView>{this.renderLikedJobs()}</ScrollView>;
  }
}

const styles = {
  detailWrapper: {
    marginBottom: 10,
    flexDirection: "row",
    justifyContent: "space-around"
  }
};

function mapStateToProps(state) {
  return { jobs: state.jobs };
}

export default connect(mapStateToProps)(ReviewScreen);
</code>```

Same thing above with this.props.likedJobs.map()

答:
I ended up refactoring my jobs reducer like so:</p>

```<code>export default function(state = INITIAL_STATE, action) {
  switch (action.type) {
    case FETCH_JOBS:
      const { listings } = action.payload;
      return { ...state, listing: listings.listing };
    default:
      return state;
  }
}
</code>```

Body:
I am working on a React Native application which has a facebook login feature that is working, the action creator and reducer is working just fine for that, but the action creators and reducers for the job search API I am using is not working.

These are the action creators:

import axios from "axios";
// import { Location } from "expo";
import qs from "qs";

import { FETCH_JOBS, LIKE_JOB } from "./types";
import locationify from "../tools/locationify";

const JOB_ROOT_URL = "https://authenticjobs.com/api/?";

const JOB_QUERY_PARAMS = {
  api_key: "<api_key>",
  method: "aj.jobs.search",
  perpage: "10",
  format: "json",
  keywords: "javascript"
};

const buildJobsUrl = () => {
  const query = qs.stringify({ ...JOB_QUERY_PARAMS });
  return `${JOB_ROOT_URL}${query}`;
};

export const fetchJobs = (
  region,
  distance = 10,
  callback
) => async dispatch => {
  try {
    const url = buildJobsUrl();
    let job_list = await axios.get(url);
    job_list = locationify(
      region,
      console.log(job_list.data.listings.listing),
      job_list.data.listings.listing,
      distance,
      (obj, coords) => {
        obj.company.location = { ...obj.company.location, coords };
        return obj;
      }
    );
    dispatch({ type: FETCH_JOBS, payload: job_list });
    callback();
  } catch (e) {
    console.log("fetchJobs Action Error:", e.message);
  }
};

export const likeJob = job => {
  return {
    payload: job,
    type: LIKE_JOB
  };
};

This is the jobs_reducer.js:

import { FETCH_JOBS } from "../actions/types";

const INITIAL_STATE = {
  listings: []
};

export default function(state = INITIAL_STATE, action) {
  switch (action.type) {
    case FETCH_JOBS:
      return action.payload;
    default:
      return state;
  }
}

This is the likes_reducer.js:

import _ from "lodash";
import { LIKE_JOB } from "../actions/types";

export default function(state = [], action) {
  switch (action.type) {
    case LIKE_JOB:
      return _.uniqBy([action.payload, ...state], "id");
    default:
      return state;
  }
}

I spent all evening yesterday debugging this and all I know is that I am console logging data to my terminal, I can see the details of the jobs API data just populate my terminal, but the error message is that the reducers are returning undefined.

How can I return data and return undefined simultaneously?

I am using an asynchronous action creator. Do I need redux-thunk on a React Native application? Am I using a version of React Native that has a bug right now? I know how Redux is supposed to work and so I am stumped here.

In reducers/index.js:

import { combineReducers } from "redux";
import auth from "./auth_reducer";
import jobs from "./jobs_reducer";
import likedJobs from "./likes_reducer";

export default combineReducers({
  auth,
  jobs,
  likedJobs
});

Where I start to get that error or what the error is referencing is the this.props.data.map() as in the components/Swipe.js:

import React, { Component } from "react";
import {
  View,
  Animated,
  PanResponder,
  Dimensions,
  LayoutAnimation,
  UIManager
} from "react-native";

const SCREEN_WIDTH = Dimensions.get("window").width;
const SWIPE_THRESHOLD = 0.25 * SCREEN_WIDTH;
const SWIPE_OUT_DURATION = 250;

class Swipe extends Component {
  static defaultProps = {
    onSwipeRight: () => {},
    onSwipeLeft: () => {},
    keyProp: "id"
  };

  constructor(props) {
    super(props);

    const position = new Animated.ValueXY();
    const panResponder = PanResponder.create({
      onStartShouldSetPanResponder: (event, gestureState) => true,
      onPanResponderMove: (event, gestureState) => {
        position.setValue({ x: gestureState.dx, y: gestureState.dy });
      },
      onPanResponderRelease: (event, gestureState) => {
        if (gestureState.dx > SWIPE_THRESHOLD) {
          this.forceSwipe("right");
        } else if (gestureState.dx < -SWIPE_THRESHOLD) {
          this.forceSwipe("left");
        } else {
          this.resetPosition();
        }
      }
    });

    this.state = { panResponder, position, index: 0 };
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.data !== this.props.data) {
      this.setState({ index: 0 });
    }
  }

  componentWillUpdate() {
    UIManager.setLayoutAnimationEnabledExperimental &&
      UIManager.setLayoutAnimationEnabledExperimental(true);
    LayoutAnimation.spring();
  }

  forceSwipe(direction) {
    const x = direction === "right" ? SCREEN_WIDTH : -SCREEN_WIDTH;
    Animated.timing(this.state.position, {
      toValue: { x, y: 0 },
      duration: SWIPE_OUT_DURATION
    }).start(() => this.onSwipeComplete(direction));
  }

  onSwipeComplete(direction) {
    const { onSwipeLeft, onSwipeRight, data } = this.props;
    const item = data[this.state.index];
    direction === "right" ? onSwipeRight(item) : onSwipeLeft(item);
    this.state.position.setValue({ x: 0, y: 0 });
    this.setState({ index: this.state.index + 1 });
  }

  resetPosition() {
    Animated.spring(this.state.position, {
      toValue: { x: 0, y: 0 }
    }).start();
  }

  getCardStyle() {
    const { position } = this.state;
    const rotate = position.x.interpolate({
      inputRange: [-SCREEN_WIDTH * 1.5, 0, SCREEN_WIDTH * 1.5],
      outputRange: ["-120deg", "0deg", "120deg"]
    });
    return {
      ...position.getLayout(),
      transform: [{ rotate }]
    };
  }

  renderCards() {
    if (this.state.index >= this.props.data.length) {
      return this.props.renderNoMoreCards();
    }

    return this.props.data
      .map((item, i) => {
        if (i < this.state.index) {
          return null;
        }

        if (i === this.state.index) {
          return (
            <Animated.View
              key={item[this.props.id]}
              style={[this.getCardStyle(), styles.cardStyle]}
              {...this.state.panResponder.panHandlers}
            >
              {this.props.renderCard(item)}
            </Animated.View>
          );
        }
        return (
          <Animated.View
            key={item[this.props.id]}
            style={[styles.cardStyle, { top: 10 * (i - this.state.index) }]}
          >
            {this.props.renderCard(item)}
          </Animated.View>
        );
      })
      .reverse();
  }

  render() {
    return <View>{this.renderCards()}</View>;
  }
}

const styles = {
  cardStyle: {
    position: "absolute",
    width: SCREEN_WIDTH
  }
};

export default Swipe;

Above I am getting that this.props.data.map() is either undefined or is not a function.

I get the same issue in ReviewScreen.js:

import React, { Component } from "react";
import { View, Text, Button, ScrollView } from "react-native";
import { connect } from "react-redux";

class ReviewScreen extends Component {
  static navigationOptions = ({ navigation }) => ({
    headerTitle: "Review Jobs",
    headerRight: (
      <Button
        title="Settings"
        onPress={() => {
          navigation.navigate("settings");
        }}
      />
    )
  });

  renderLikedJobs() {
    return this.props.likedJobs.map(job => {
      return (
        <Card>
          <View style={{ height: 200 }}>
            <View style={styles.detailWrapper}>
              <Text style={styles.italics}>{job.company}</Text>
              <Text style={styles.italics}>{job.post_date}</Text>
            </View>
          </View>
        </Card>
      );
    });
  }

  render() {
    return <ScrollView>{this.renderLikedJobs()}</ScrollView>;
  }
}

const styles = {
  detailWrapper: {
    marginBottom: 10,
    flexDirection: "row",
    justifyContent: "space-around"
  }
};

function mapStateToProps(state) {
  return { jobs: state.jobs };
}

export default connect(mapStateToProps)(ReviewScreen);

Same thing above with this.props.likedJobs.map()

Body:
I ended up refactoring my jobs reducer like so:

export default function(state = INITIAL_STATE, action) {
  switch (action.type) {
    case FETCH_JOBS:
      const { listings } = action.payload;
      return { ...state, listing: listings.listing };
    default:
      return state;
  }
}


答:
You need to put breaks in a switch statement if you don't want the default to run. Just do this:

```<code>var people = {
    names : ["Sam", "Tim", "Steve"],
    emails : ["sam@email.com", "timm@messages.org", "stevieG@youhavemail.com"],
    phonenums : [1111, 2222, 4545]
}

var search = prompt("Type in someone's name to find their phone number and email.");
switch(search) {
    case people.names[0]:
        alert(people.names[0] + "'s email: " + people.emails[0] + " phone number: " + people.phonenums[0]);
        break;

    case people.names[1]:
        alert(people.names[1] + "'s email: " + people.emails[1] + " phone number: " + people.phonenums[1]);
        break;

    case people.names[2]:
        alert(people.names[2] + "'s email: " + people.emails[2] + " phone number: " + people.phonenums[2]);
        break;

    default:
        alert("I don't know that person.");
}
</code>```

In your particular scenario, you may be better off searching for the index of the correct person and using that so your array is free to grow and shrink. Something like this could work:

```<code>var search = prompt("Type in someone's name to find their phone number and email.");
boolean found = false;
int i = 0;
while(!found && i<people.names.length) {
    if(people.names[0] == search){
        found=true;
    } else {
        i++;
    }
}
if(found){
        alert(people.names[i] + "'s email: " + people.emails[i] + " phone number: " + people.phonenums[i]);
} else {
        alert("I don't know that person.");
}
</code>```

My js is rusty and I'm using my phone, I'll check later for syntax errors if no one else spots any.

Body:
I have a switch statement. It almost works fine, however instead of just showing one case, it shows the selected case then the default. Here is my code:

var people = {
  names: ["Sam", "Tim", "Steve"],
  emails: ["sam@email.com", "timm@messages.org", "stevieG@youhavemail.com"],
  phonenums: [1111, 2222, 4545]
}

var search = prompt("Type in someone's name to find their phone number and email.");

switch (search) {
  case people.names[0]:
    alert(people.names[0] + "'s email: " + people.emails[0] + " phone number: " + people.phonenums[0]);
  case people.names[1]:
    alert(people.names[1] + "'s email: " + people.emails[1] + " phone number: " + people.phonenums[1]);
  case people.names[2]:
    alert(people.names[2] + "'s email: " + people.emails[2] + " phone number: " + people.phonenums[2]);
  default:
    alert("I don't know that person.");
}

Why does this happen?

Body:
You need to put breaks in a switch statement if you don't want the default to run. Just do this:

var people = {
    names : ["Sam", "Tim", "Steve"],
    emails : ["sam@email.com", "timm@messages.org", "stevieG@youhavemail.com"],
    phonenums : [1111, 2222, 4545]
}

var search = prompt("Type in someone's name to find their phone number and email.");
switch(search) {
    case people.names[0]:
        alert(people.names[0] + "'s email: " + people.emails[0] + " phone number: " + people.phonenums[0]);
        break;

    case people.names[1]:
        alert(people.names[1] + "'s email: " + people.emails[1] + " phone number: " + people.phonenums[1]);
        break;

    case people.names[2]:
        alert(people.names[2] + "'s email: " + people.emails[2] + " phone number: " + people.phonenums[2]);
        break;

    default:
        alert("I don't know that person.");
}

In your particular scenario, you may be better off searching for the index of the correct person and using that so your array is free to grow and shrink. Something like this could work:

var search = prompt("Type in someone's name to find their phone number and email.");
boolean found = false;
int i = 0;
while(!found && i<people.names.length) {
    if(people.names[0] == search){
        found=true;
    } else {
        i++;
    }
}
if(found){
        alert(people.names[i] + "'s email: " + people.emails[i] + " phone number: " + people.phonenums[i]);
} else {
        alert("I don't know that person.");
}

My js is rusty and I'm using my phone, I'll check later for syntax errors if no one else spots any.


问:
How to build reactive architecture that will avoid nested Flux blocks (Flux<Flux <T>>)?
I am trying to build an application A (like an adaptor) that will:

1) Receive POST requests with some key (JSON format)

2) It should modify that key somehow and create POST request to another system B.

3) Application A should parse the response from application B and modify that response.

4) After that my application A should answer to the initial POST request.

```<code>@RestController
@RequestMapping("/A")
public class Controller {
    @ResponseStatus(HttpStatus.OK)
    @PostMapping(value = "B", consumes = APPLICATION_JSON_VALUE)
    // to return nested Flux is a bad idea here
    private Flux<Flux<Map<String, ResultClass>>> testUpdAcc(@RequestBody Flux<Map<String, SomeClass>> keys) {
        return someMethod(keys);
    }

    // the problem comes here when I will get Flux<Flux<T>> in the return
    public Flux<Flux<Map<String, ResultClass>>> someMethod(Flux<Map<String, SomeClass>> keysFlux) {
        return keysFlux.map(keysMap -> {
                                // do something with keys and create URL
                                // also will batch keys here
                                <...>

                                // for each batch of keys:
                                WebClient.create(hostAndPort)
                                .method(HttpMethod.POST)
                                .uri(url)
                                .body(BodyInserters.fromObject(body))
                                .header(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded")
                                .accept(MediaType.APPLICATION_JSON)
                                .retrieve()
                                .bodyToMono(schema) // response will be parsed into some schema here
                                .retryWhen (// will make a retry mechanism here)

                                // ===== will join all Mono batches into single Flux
                                Flux.concat(...);
                                }
                             );
    }

}
</code>```

Of course this can be fixed by not reading keysFlux as Flux and read that as Map. But that should make everything less reactive, no? :)

```<code>    @ResponseStatus(HttpStatus.OK)
    @PostMapping(value = "B", consumes = APPLICATION_JSON_VALUE)
    // to return nested Flux is a bad idea here
    private Flux<Map<String, ResultClass>> testUpdAcc(@RequestBody Map<String, SomeClass> keys) {
        return someMethod(keys);
    }
</code>```

Also I have tried to use block()/blockFirst() in the last moment before returning the request, but I have got an error:

```<code>block()/blockFirst()/blockLast() are blocking, which is not supported in thread reactor...
</code>```

Thank you for your ideas!

答:
Try to zip all the flux like this

```<code>Flux.zip(flux1,flux2)
</code>```

It will create Tuple2 so that you can do flatMap

Thanks,

Vimalesh

Body:
I am trying to build an application A (like an adaptor) that will:

1) Receive POST requests with some key (JSON format)

2) It should modify that key somehow and create POST request to another system B.

3) Application A should parse the response from application B and modify that response.

4) After that my application A should answer to the initial POST request.

@RestController
@RequestMapping("/A")
public class Controller {
    @ResponseStatus(HttpStatus.OK)
    @PostMapping(value = "B", consumes = APPLICATION_JSON_VALUE)
    // to return nested Flux is a bad idea here
    private Flux<Flux<Map<String, ResultClass>>> testUpdAcc(@RequestBody Flux<Map<String, SomeClass>> keys) {
        return someMethod(keys);
    }

    // the problem comes here when I will get Flux<Flux<T>> in the return
    public Flux<Flux<Map<String, ResultClass>>> someMethod(Flux<Map<String, SomeClass>> keysFlux) {
        return keysFlux.map(keysMap -> {
                                // do something with keys and create URL
                                // also will batch keys here
                                <...>

                                // for each batch of keys:
                                WebClient.create(hostAndPort)
                                .method(HttpMethod.POST)
                                .uri(url)
                                .body(BodyInserters.fromObject(body))
                                .header(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded")
                                .accept(MediaType.APPLICATION_JSON)
                                .retrieve()
                                .bodyToMono(schema) // response will be parsed into some schema here
                                .retryWhen (// will make a retry mechanism here)

                                // ===== will join all Mono batches into single Flux
                                Flux.concat(...);
                                }
                             );
    }

}

Of course this can be fixed by not reading keysFlux as Flux and read that as Map. But that should make everything less reactive, no? :)

    @ResponseStatus(HttpStatus.OK)
    @PostMapping(value = "B", consumes = APPLICATION_JSON_VALUE)
    // to return nested Flux is a bad idea here
    private Flux<Map<String, ResultClass>> testUpdAcc(@RequestBody Map<String, SomeClass> keys) {
        return someMethod(keys);
    }

Also I have tried to use block()/blockFirst() in the last moment before returning the request, but I have got an error:

block()/blockFirst()/blockLast() are blocking, which is not supported in thread reactor...

Thank you for your ideas!

Body:
Try to zip all the flux like this

Flux.zip(flux1,flux2)

It will create Tuple2 so that you can do flatMap

Thanks,

Vimalesh


问:
Table tbody not correctly appending
My table tbody doesn't display the correct data after an AJAX GET request. Well actually, after the second iteration of my for loop, it is showing correctly, but after the third iteration and so on, it is appending but it is showing the previous item.

This is what it showing:

I don't know why it is showing incorrectly in the table in console log, the data is showing correctly.

$.ajax({
  cache: false,
  type: 'GET',
  url: '@Url.Action("DisplayFiles","FileUploader")', //url, // '/Account/Delete/',
  dataType: "json",
  success: function(response) {
    $("#tblFiles tbody").remove();

    for (var i = 0; i < response.length; i++) {
      console.log(response[i]['Filename']);
      console.log(response[i]['FileFullPath']);

      $("#tblFiles").append('
' + response[i]['Filename'] + '	' + response[i]['FileFullPath'] + '
');

      //var tbodyFiles = "
 " + response[i]['Filename'] + "	" + " " + response[i]['FileFullPath'] + "
";
    }

    //$("#tblFiles").append(tbodyFiles);
    console.log(response);
  },
  error: function(resp) {
    console.log('error');
  }
});
```

<pre class="lang-html prettyprint-override"><code><table class="table table-striped" id="tblFiles">
  <thead>
    <tr>
      <th>Filename</th>
      <th>File Fullpath</th>
      @*
      <th>Date Added</th>*@
      <th></th>
    </tr>
  </thead>
  <tbody>
    @foreach (var item in Model) {
    <tr>
      <td>
        @Html.DisplayFor(modelItem => item.Filename)
      </td>
      <td>
        @Html.DisplayFor(modelItem => item.FileFullPath)
      </td>
      @*
      <td>
        @Html.DisplayFor(modelItem => item.DateAdded)
      </td>
      *@
      <td>
        @Html.ActionLink(" ", "Delete", new { id = item.Id }, new { @class = "btn-xs btn btn-danger glyphicon glyphicon-trash" })
      </td>
    </tr>
    }
  </tbody>
</table>
</code>```

答:
Change this:

$("#tblFiles tbody").remove();

to this:

$("#tblFiles tbody tr").remove();

and then change this:

$("#tblFiles").append(...)

to this:

$('#tblFiles tbody").append(...)

Explanation:

You were removing the entire tbody element, but appending the trs to the table not the tbody.

The proposed changes will ensure that the tbody stays present and that trs are added as children to it instead of outside of it.

Title: Table tbody not correctly appending

Body:
My table tbody doesn't display the correct data after an AJAX GET request. Well actually, after the second iteration of my for loop, it is showing correctly, but after the third iteration and so on, it is appending but it is showing the previous item.

This is what it showing:

I don't know why it is showing incorrectly in the table in console log, the data is showing correctly.

$.ajax({
  cache: false,
  type: 'GET',
  url: '@Url.Action("DisplayFiles","FileUploader")', //url, // '/Account/Delete/',
  dataType: "json",
  success: function(response) {
    $("#tblFiles tbody").remove();

    for (var i = 0; i < response.length; i++) {
      console.log(response[i]['Filename']);
      console.log(response[i]['FileFullPath']);

      $("#tblFiles").append('
' + response[i]['Filename'] + '	' + response[i]['FileFullPath'] + '
');

      //var tbodyFiles = "
 " + response[i]['Filename'] + "	" + " " + response[i]['FileFullPath'] + "
";
    }

    //$("#tblFiles").append(tbodyFiles);
    console.log(response);
  },
  error: function(resp) {
    console.log('error');
  }
});

      Filename
      File Fullpath
      @*
      Date Added	*@

    @foreach (var item in Model) {

        @Html.DisplayFor(modelItem => item.Filename)

        @Html.DisplayFor(modelItem => item.FileFullPath)

      @*

        @Html.DisplayFor(modelItem => item.DateAdded)

      *@

        @Html.ActionLink(" ", "Delete", new { id = item.Id }, new { @class = "btn-xs btn btn-danger glyphicon glyphicon-trash" })

    }


问:
Creating Index on Table in a schema
I am logged in as 'sa', with full admin rights, and I am running the following command:

```<code>CREATE NONCLUSTERED INDEX [IDX_EntityAuditId] ON [Maintenance.EntityAuditMessagesArchive]
([EntityAuditId] ASC) ON [PRIMARY]
</code>```

and getting the error:

Cannot find the object "Maintenance.EntityAuditMessagesArchive" because it does not exist or you do not have permissions.

The object does exist, because I can select from it. Furthermore, the command works if the table is not in a schema. i.e.

```<code>CREATE NONCLUSTERED INDEX [IDX_EntityAuditId] ON [EntityAuditMessagesArchive]
    ([EntityAuditId] ASC) ON [PRIMARY]
</code>```

works (when I create the table without a schema, of course).

So, I can't create the index when the table is in the Maintenance schema. Why is this?

答:
You have a . in your name.  I'm guessing you need to change it to:

[Maintenance].[EntityAuditMessagesArchive]

A period inside the brackets indicates it is a part of the name, not a separator.

Title: Creating Index on Table in a schema

Body:
I am logged in as 'sa', with full admin rights, and I am running the following command:

CREATE NONCLUSTERED INDEX [IDX_EntityAuditId] ON [Maintenance.EntityAuditMessagesArchive]
([EntityAuditId] ASC) ON [PRIMARY]

and getting the error:

Cannot find the object "Maintenance.EntityAuditMessagesArchive" because it does not exist or you do not have permissions.

The object does exist, because I can select from it. Furthermore, the command works if the table is not in a schema. i.e.

CREATE NONCLUSTERED INDEX [IDX_EntityAuditId] ON [EntityAuditMessagesArchive]
    ([EntityAuditId] ASC) ON [PRIMARY]

works (when I create the table without a schema, of course).

So, I can't create the index when the table is in the Maintenance schema. Why is this?


问:
How to remove duplicate words from a text file using java
I have a input file like

names.txt

```<code>   Maria Derek Erica
   Livia Jack Anita
   Kendall Maria Livia Derek
   Jamie Jack
   Thomson Erica

</code>```

I want to output like. Removing duplicates words from the name

output.txt

```<code>   Maria Derek Erica
   Livia Jack Anita
   Kendall
   Jamie
   Thomson

</code>```

I already tried to read file separated by whitespace and then add them into ArrayList then I lost what to do next to generate output.

import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;

public class duplicate {
   public static void main(String[] args) throws IOException {
      ArrayList<String> list = new ArrayList<String>();
      File file = new File("weather.txt");
      Scanner input = new Scanner(file);
      String prev = input.next();
      int count = 0;
      while (input.hasNext()) {
         String next  = input.next();
         System.out.println(next);
         set.add(next);
         count = count + 1;
         if(prev.equals(next))
         {
            System.out.println("Match found: -" + prev);
         }
         prev = next;
      }

      System.out.println(list);
      System.out.println("Word count: " + count);
   }
}
```

答:
```<code>import java.util.Scanner;
import java.io.*;
import java.util.HashSet;

public class Duplicate {
    public static void main(String[] args) throws IOException {
        HashSet<String> lines = new HashSet<String>();
        File file = new File("weather.txt");
        Scanner input = new Scanner(file);
        int count = 0;
        while (input.hasNext()) {
            String next  = input.next();
            System.out.println(next);
            lines.add(next);
            count++;
        }
        input.close();
        System.out.println(lines);
        System.out.println("Word count: " + count);
        System.out.println("Unique word count: " + lines.size());
    }
}
</code>```

Body:
I have a input file like

names.txt

   Maria Derek Erica
   Livia Jack Anita
   Kendall Maria Livia Derek
   Jamie Jack
   Thomson Erica

I want to output like. Removing duplicates words from the name

output.txt

   Maria Derek Erica
   Livia Jack Anita
   Kendall
   Jamie
   Thomson

I already tried to read file separated by whitespace and then add them into ArrayList then I lost what to do next to generate output.

import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;

public class duplicate {
   public static void main(String[] args) throws IOException {
      ArrayList<String> list = new ArrayList<String>();
      File file = new File("weather.txt");
      Scanner input = new Scanner(file);
      String prev = input.next();
      int count = 0;
      while (input.hasNext()) {
         String next  = input.next();
         System.out.println(next);
         set.add(next);
         count = count + 1;
         if(prev.equals(next))
         {
            System.out.println("Match found: -" + prev);
         }
         prev = next;
      }

      System.out.println(list);
      System.out.println("Word count: " + count);
   }
}


问:
@BatchFetch type JOIN
I'm confused about this annotation for an entity field that is of type of another entity:

```<code>@BatchFetch(value = BatchFetchType.JOIN)
</code>```

In the docs of EclipseLink for BatchFetch they explain it as following:

For example, consider an object with an EMPLOYEE and PHONE table in
  which PHONE has a foreign key to EMPLOYEE. By default, reading a list
  of employees' addresses by default requires n queries, for each
  employee's address. With batch fetching, you use one query for all the
  addresses.

but I'm confused about the meaning of specifying BatchFetchType.JOIN. I mean, doesn't BatchFetch do a join in the moment it retrieves the list of records associated with employee? The records of address/phone type are retrieved using the foreign key, so it is a join itself, right?

The BatchFetch type is an optional parameter, and for join it is said:

JOIN – The original query's selection criteria is joined with the
  batch query

what does this means? Isn't the batch query a join itself?

答:
Joining the relationship and returning the referenced data with the main data is a fetch join. So a query that brings in 1 Employee that has 5 phones, results in 5 rows being returned, with the data in Employee being duplicated for reach row. When that is less ideal, say a query over 1000 employees, you resort to a separate batch query for these phone numbers. Such a query would run once to return 1000 employee rows, and then run a second query to return all employee phones needed to build the read in employees.

The three batch query types listed here then determine how this second batch query gets built. These will perform differently based on the data and database tuning.

JOIN - Works much the same away a fetch join would, except it only returns the Phone data.

EXISTS -  This causes the DB to execute the initial query on Employees, but uses the data in an Exists subquery to then fetch the Phones.

IN - EclipseLink agregates all the Employee IDs or values used to reference Phones, and uses them to filter Phones directly.

Best way to find out is always to try it out with SQL logging turned on to see what it generates for your mapping and query. Since these are performance options, you should test them out and record the metrics to determine which works best for your application as its dataset grows.

Title: @BatchFetch type JOIN

Body:
I'm confused about this annotation for an entity field that is of type of another entity:

@BatchFetch(value = BatchFetchType.JOIN)

In the docs of EclipseLink for BatchFetch they explain it as following:

For example, consider an object with an EMPLOYEE and PHONE table in
  which PHONE has a foreign key to EMPLOYEE. By default, reading a list
  of employees' addresses by default requires n queries, for each
  employee's address. With batch fetching, you use one query for all the
  addresses.

but I'm confused about the meaning of specifying BatchFetchType.JOIN. I mean, doesn't BatchFetch do a join in the moment it retrieves the list of records associated with employee? The records of address/phone type are retrieved using the foreign key, so it is a join itself, right?

The BatchFetch type is an optional parameter, and for join it is said:

JOIN – The original query's selection criteria is joined with the
  batch query

what does this means? Isn't the batch query a join itself?